How can I get a port through a website through C # from IIS?

In IIS-Manager, the website is bound to port 80 by default. How can I get the port by the name of the website 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 job is var lPort = lServerManager.Sites[lWebsite] .

+6
source share
1 answer

When you access the [lWebsite] .Bindings sites, you gain access to the bindings collection. When you try to call GetAttributeValue ("Port"), it fails because it does not make sense - the collection itself does not have a port number associated with it, it's just a collection.

If you want to access the port number used by each binding, you need to cycle through these bindings and set each of them with its own port number:

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

It is worth emphasizing the fact that websites can be connected to multiple ports. You are talking about getting a β€œport”, but this is not necessarily the case, for example, a website that serves both HTTP and HTTPS will have two bindings, usually on ports 80 and 443. That's why you have to deal with collection of bindings, although in your case this collection can contain only one binding, which is still a collection.

See the MSDN documentation for the Binding class for more information. Please note that some of the things you might be interested in will be related to accessing the EndPoint binding object, as in the example above.

+10
source

All Articles