如何从web.config system.web和system.webServer中读取Ihttpmodule

时间:2013-07-18 04:06:14

标签: asp.net web-config

web.config看起来像:


   <system.web>
   <httpModules>
  <add name="DotNetCasClient" type="DotNetCasClient.CasAuthenticationModule,DotNetCasClient"/>
    </httpModules>
  </system.web>
     <system.webServer>
     <modules>
    <remove name="DotNetCasClient"/>
    <add name="DotNetCasClient" type="DotNetCasClient.CasAuthenticationModule,DotNetCasClient"/>
      </modules>
 </system.webServer>

在C#代码中:

  [assembly: PreApplicationStartMethod(typeof(CasClientStart), "Start")]

 namespace Dev.CasClient
 {

public static class CasClientStart
{

    /// <summary>
    ///     Starts the application
    /// </summary>
    public static void Start()
    {
        if( !..... Registered (DotNetCasClient) In Web.config)
        DynamicModuleUtility.RegisterModule(typeof(DotNetCasClient));

    }
   }
   }

如何从web.config中读取httpmodule? 在动态注册模块之前,我想先查看Web.confg。


我的解决方案,

   // the Final Solution
    public static void Start()
    {
       var IWantReg = typeof(CasClientModule).FullName;
        var Configuration = WebConfigurationManager.OpenWebConfiguration("~");
    if (HttpRuntime.UsingIntegratedPipeline)
    {
        var websermodules = Configuration.GetSection("system.webServer");

        var xml = websermodules.SectionInformation.GetRawXml();

        XDocument xmlFile = XDocument.Load(new StringReader(xml));
        IEnumerable<XElement> query = from c in xmlFile.Descendants("modules").Descendants("add") select c;

        foreach (XElement band in query)
        {
            var attr = band.Attribute("type");

            var strType = attr.Value.Split(',').First();

            if (strType.ToLower() == IWantReg.ToLower())
                return;
        }
    }
    else
    {
        object o = Configuration.GetSection("system.web/httpModules");
        HttpModulesSection section = o as HttpModulesSection;
        var models = section.Modules;

        foreach (HttpModuleAction model in models)
        {
            if (model.Type.Split(',').First() == IWantReg)
                return;
        }
    }


    DynamicModuleUtility.RegisterModule(typeof(CasClientModule));

}
  

终于解决了这个问题,分别通过集成与经典格式两种方式。感谢朋友们的帮助。

2 个答案:

答案 0 :(得分:2)

这对你有用吗? (另)

Configuration Configuration =  WebConfigurationManager.OpenWebConfiguration("~");
object o = Configuration.GetSection("system.web/httpModules");
HttpModulesSection section = o as HttpModulesSection;
var kvp = section.CurrentConfiguration.AppSettings.Settings["Name"];

答案 1 :(得分:0)

尝试使用类似

的内容
(HttpModulesSection)ConfigurationManager.GetSection("system.web/httpModules");

这将读取web.config文件的modules部分。如果您只想阅读已加载的模块,请使用:

HttpModuleCollection modules = HttpContext.Current.ApplicationInstance.Modules;
foreach (string moduleKey in modules.Keys)
{
    IHttpModule module = modules[moduleKey];
    // Do what you want with the loaded module
}

更多信息: Detecting if a HttpModule is loaded