如何在ApplicationHost.config中为C#上的IIS服务器上的所有网站添加HttpModule?

问题描述:

我想是这样如何在ApplicationHost.config中为C#上的IIS服务器上的所有网站添加HttpModule?

public string[] RegisterInApplicationConfig() 
    { 
     using (ServerManager serverManager = new ServerManager()) 
     { 
      Configuration config = serverManager.GetApplicationHostConfiguration(); 
      var section = config.GetSection("location/system.webServer/modules"); 

     } 
    } 

,但错误,我得到的是 -

的配置,因为它缺少一个部分声明部分location/system.webServer/modules无法读取。

我指从增加后的HttpModule -

How do I register a HttpModule in the machine.config for IIS 7?

所以在ApplicationHostConfig基本上,我需要去

<location path="" overrideMode="Allow"> 
    <system.webServer> 

    <modules> 
     <add name="IsapiFilterModule" lockItem="true" /> 

所以我找到了解决办法之后,一些打&试验。可能有助于有人在面向未来

我需要的“system.webServer/modules”部分做GetCollection

Configuration config = serverManager.GetApplicationHostConfiguration(); 
      var section = config.GetSection("system.webServer/modules", ""); 
      var collection = section.GetCollection(); 
      var element = collection.CreateElement(); 
      element.Attributes["name"].Value = "MyHttpModule"; 
      element.Attributes["type"].Value = MyHttpModule.XXXModule, MyHttpModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bc88fbd2dc8888795"; 
      collection.Add(element); 
      serverManager.CommitChanges();