【问题标题】:Get HTTPModule's own parameters in web.config?在 web.config 中获取 HTTPModule 自己的参数?
【发布时间】:2015-11-23 07:09:12
【问题描述】:

我正在创建一个 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>

但我能找到的大部分信息是this。我说,是的,我可以获得整个 &lt;modules&gt; 标签,但是我的 HTTPModule 的每个实例如何知道要采用哪些参数?如果我可以在创建时获得名称(tpl01tpl02),我可以在之后按名称查找它的参数,但我没有在 HTTPModule 类中看到任何属性来获得它。

非常欢迎任何帮助。提前致谢! :)

【问题讨论】:

  • HttpModuleCollection 有一个 AllKeys 属性。对于每个键,您可以 Get(key) 并检查返回是否等于模块的 this 以确定模块的名称。

标签: c# asp.net web-config arguments httpmodule


【解决方案1】:

我认为,这部分配置(system.webServer\modules\add)不是为了将参数传递(存储)给模块,而是为了注册模块列表来处理请求。

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

【讨论】:

    【解决方案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);
        }
    
        // ...
    }
    

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

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

    【讨论】:

    • 这只是一个等待发生的可怕的竞争条件错误。在基类中创建一个新的虚拟方法,并使用来自子类的不同参数调用它。不要不要使用静态字段来传递参数,这很愚蠢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2023-03-03
    • 2013-03-30
    • 2019-01-06
    相关资源
    最近更新 更多