Question

In IIS-Manager, the default web site is bound on port 80. How can I get the port by website-name, using c#? I tried the following code:

var lWebsite = "Default Web Site";
var lServerManager = new ServerManager();
var lPort = lServerManager.Sites[lWebsite].Bindings.GetAttributeValue("Port");

lPort results in null with an invalid index exception. But the assignment var lPort = lServerManager.Sites[lWebsite] works.

Was it helpful?

Solution

When you access Sites[lWebsite].Bindings, you're accessing a collection of bindings. When you then try to call GetAttributeValue("Port"), it fails because that makes no sense - the collection itself doesn't have a port number associated with it, it's just a collection.

If you want to get access to the port number used by each binding, you need to loop through those bindings and ask each one for its associated port number:

var site = lServerManager.Sites[lWebsite];
foreach (var binding in site.Bindings)
{
    int port = binding.EndPoint.Port;
    // Now you have this binding's port, and can do whatever you want with it.
}

It's worth highlighting the fact that websites can be bound to multiple ports. You talk about getting "the" port, but that's not necessarily the case - for example, a website that's served over both HTTP and HTTPS will have two bindings, usually on ports 80 and 443. That's why you're having to deal with a collection of bindings, even though in your case that collection may only contain one binding it's still a collection.

For further details, have a look at the MSDN documentation for the Binding class. Note that some of what you're likely to be interested in will involve accessing the binding's EndPoint property, as in the sample above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top