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

本文关键字:httpmodule 自己的 参数 获取 web config | 更新日期: 2023-09-27 18:10:19

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

不管怎样,我想要我的网。这样配置:

<system.webServer>
    <modules>
        <add name="tpl01" type="TemplateModule" arg1="~/" arg2="500" />    
        <add name="tpl02" type="TemplateModule" arg1="~/" arg2="100" />    
    </modules>
</system.webServer>

但我能找到的最多的信息是这样的。我说,是的,我可以获得整个<modules>标签,但我的HTTPModule的每个实例如何知道采取哪些参数?如果我能在创建时获得名称(tpl01tpl02),我可以在之后按名称查找它的参数,但我没有看到HTTPModule类中的任何属性来获得它。

任何帮助都是非常欢迎的。提前感谢!:)

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

我认为,这部分配置(系统)。webServer'modules'add)不打算传递(存储)参数给模块,而是注册处理请求的模块列表。

关于"add"元素中可能的属性,请参见- https://msdn.microsoft.com/en-us/library/ms690693(v=vs.90).aspx

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

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

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);
    }
    // ...
}

然后,在你的web应用中,每次你需要用一组不同的值来使用模块时,继承该模块并覆盖这些字段:

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