Search code examples
c#asp.netweb-configargumentshttpmodule

Get HTTPModule's own parameters in web.config?


I'm creating an HTTPModule which can be reused a few times, but with different parameters. Think as an example, a request redirector module. I could use an HTTPHandler but it is not a task for it because my process needs to work at the request level, not at an extension/path level.

Anyways, I'd like to have my web.config this way:

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

But most information I could find was this. I say, yeah, I can obtain the whole <modules> tag, but how do each instance of my HTTPModule knows which arguments to take? If I could get the name (tpl01 or tpl02) upon creation, I could look its arguments up by name afterwards, but I did not see any property in the HTTPModule class to get that.

Any help would be really welcome. Thanks in advance! :)


Solution

  • This could be a workaround for your issue.

    First, define your module with fields for what you need to set from outside:

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

    Then, from your web app, every time you need to use the module with a different set of those values, inherit the module and override the fields:

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