2013-10-31 81 views
3

我正在尋找一種方法來使用Microsoft.Web.Administration.dll在IIS 7中添加處理程序映射。有沒有我可以在ServerManager對象上使用的方法?如何以編程方式添加IIS處理程序映射

這些是通過GUI添加時要遵循的步驟,但同樣需要通過編程來完成。 http://coderock.net/how-to-create-a-handler-mapping-for-an-asp-net-iis-7-with-application-running-in-integrated-mode/

這是我用來啓用ISAPI限制的代碼,有沒有類似的處理程序映射?

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(); 
    } 
} 

回答

9

這是我最終使用的解決方案:

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(); 
     } 
    } 
} 
相關問題