Sunday, January 23, 2011

Get IIS bindings at runtime without being an Administrator

Today there was a question in StackOverflow asking whether it was possible to read the IIS binding information such as Port and Protocols from the ASP.NET application itself to try to handle redirects from HTTP to HTTPS in a way that was reliable without worrying about using different ports than 80/443.
Turns out this is possible in the context of the IIS worker process by using Microsoft.Web.Administration.
The following function will take care of that by reading the Worker Process isolated configuration file and find the HTTP based bindings.

private static IEnumerable<KeyValuePair<string, string>> GetBindings(HttpContext context) {
       // Get the Site name
       string siteName = System.Web.Hosting.HostingEnvironment.SiteName;
       // Get the sites section from the AppPool.config
       Microsoft.Web.Administration.ConfigurationSection sitesSection =
           Microsoft.Web.Administration.WebConfigurationManager.GetSection(null, null, "system.applicationHost/sites");
       
       foreach (Microsoft.Web.Administration.ConfigurationElement site in sitesSection.GetCollection()) {
           // Find the right Site
           if (String.Equals((string)site["name"], siteName, StringComparison.OrdinalIgnoreCase)) {
               // For each binding see if they are http based and return the port and protocol

Read more: CarlosAg Blog