Search code examples
c#iis-7

How to add IIS handler mapping programmatically


I'm looking for a way to add a handler mapping in IIS 7 using Microsoft.Web.Administration.dll. Is there a method I can use on the ServerManager object?

These are the steps to follow if adding through the GUI, but again, I need to accomplish this programmatically. http://coderock.net/how-to-create-a-handler-mapping-for-an-asp-net-iis-7-with-application-running-in-integrated-mode/

This is the code I am using to enable ISAPI restrictions, is there something similar for handler mappings?

public override void AddIsapiAndCgiRestriction(string description, string path, bool isAllowed)
{
    using (ServerManager serverManager = new ServerManager())
    {
        Configuration config = serverManager.GetApplicationHostConfiguration();
        ConfigurationSection isapiCgiRestrictionSection = config.GetSection("system.webServer/security/isapiCgiRestriction");
        ConfigurationElementCollection isapiCgiRestrictionCollection = isapiCgiRestrictionSection.GetCollection();
        ConfigurationElement addElement = isapiCgiRestrictionCollection.CreateElement("add");
        addElement["path"] = path;
        addElement["allowed"] = isAllowed;
        addElement["description"] = description;
        isapiCgiRestrictionCollection.Add(addElement);
        serverManager.CommitChanges();
    }
}

Solution

  • This is the solution I ended up using:

    public void AddHandlerMapping(string siteName, string name, string executablePath)
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration siteConfig = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection handlersSection = siteConfig.GetSection("system.webServer/handlers", siteName);
            ConfigurationElementCollection handlersCollection = handlersSection.GetCollection();
    
            bool exists = handlersCollection.Any(configurationElement => configurationElement.Attributes["name"].Value.Equals(name));
    
            if (!exists)
            {
                ConfigurationElement addElement = handlersCollection.CreateElement("add");
                addElement["name"] = name;
                addElement["path"] = "*";
                addElement["verb"] = "*";
                addElement["modules"] = "IsapiModule";
                addElement["scriptProcessor"] = executablePath;
                addElement["resourceType"] = "Unspecified";
                addElement["requireAccess"] = "None";
                addElement["preCondition"] = "bitness32";
                handlersCollection.Add(addElement);
                serverManager.CommitChanges();
            }
        }
    }