在web.config中获取HTTPModule自己的参数?

DAR*_*Guy 5 c# asp.net arguments web-config httpmodule

我正在创建一个HTTPModule,可以重复使用几次,但参数不同.以一个请求重定向器模块为例.我可以使用HTTPHandler,但它不是一个任务,因为我的进程需要在请求级别工作,而不是在扩展/路径级别.

无论如何,我想以这种方式拥有我的web.config:

<system.webServer>
    <modules>
        <add name="tpl01" type="TemplateModule" arg1="~/" arg2="500" />    
        <add name="tpl02" type="TemplateModule" arg1="~/" arg2="100" />    
    </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

但我能找到的大部分信息都是这样的.我说,是的,我可以获得整个<modules>标记,但我的HTTPModule的每个实例如何知道要采用哪些参数?如果我可以在创建时获得名称(tpl01tpl02),我可以在之后通过名称查看其参数,但我没有在HTTPModule类中看到任何属性来获取它.

任何帮助都会非常受欢迎.提前致谢!:)

zed*_*zed -2

这可能是解决您的问题的方法。

首先,使用您需要从外部设置的字段定义您的模块:

public class TemplateModule : IHttpModule
{
    protected static string _arg1;
    protected static string _arg2;

    public void Init(HttpApplication context)
    {
        _arg1 = "~/";
        _arg2 = "0";

        context.BeginRequest += new EventHandler(ContextBeginRequest);
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的网络应用程序中,每次您需要使用具有不同组值的模块时,继承该模块并覆盖这些字段:

public class TemplateModule01 : Your.NS.TemplateModule
{
    protected override void ContextBeginRequest(object sender, EventArgs e)
    {
        _arg1 = "~/something";
        _arg2 = "500";

        base.ContextBeginRequest(sender, e);
    }
}

public class TemplateModule02 : Your.NS.TemplateModule
{
    protected override void ContextBeginRequest(object sender, EventArgs e)
    {
        _arg1 = "~/otherthing";
        _arg2 = "100";

        base.ContextBeginRequest(sender, e);
    }
}
Run Code Online (Sandbox Code Playgroud)