1
votes

I am currently developing an ASP.NET MVC 3 site using Visual Studio 2010 with SSL enabled for debugging on my local machine via IIS Express. A port is assigned for http and https in the applicationhost.config file for my site.

For the sake of example, let's say my http port is 3333, and my https port is 6666.

Is there a way to access these port numbers that are configured in IIS Express programatically in my ASP.NET code?

I can access the port number I am currently using, ie. if I am hitting a page at http://localhost:3333/somepage, then I can get at the 3333, but I want to be able to get the 6666 from the web server configuration.

1
What problem are you trying to solve with this? If you need to redirect to the SSL version, there are other ways.Alex Moore
I'm trying to write an attribute that can be put on an action that can toggle between http and https. Similar to the RequireHttpsAttribute except that you can specify requires http or https. In my development environment this requires including the port number. Easy enough to hard code but would love to be able to pull it from the server configuration somehow.bingles

1 Answers

1
votes

You can get the ports using the Binding class of Microsoft.Web.Administration. Below is an example.

using (ServerManager sm = new ServerManager())
{
    var bindings = sm.Sites[HostingEnvironment.ApplicationHost.GetSiteName()].Bindings;
    foreach (Binding b in bindings)
    {
        if (b.IsIPPortHostBinding)
        {
            if (b.Protocol.Equals("http"))
                Debug.WriteLine("HTTP port is " +  b.EndPoint.Port);
            else if (b.Protocol.Equals("https"))
                Debug.WriteLine("HTTPS port is " + b.EndPoint.Port);
        }

    }
}