Search code examples
asp.nethttpmodule

getting access to property of HttpModule from page


Is there a way to get access to a property of HttpModule from asp.net page?

namespace MyHttpModule
{
    public class Module : IHttpModule
    {
        public string M_Property { get; set; }

        public void Init(HttpApplication context)
        {

Solution

  • You can get active modules from ApplicationInstance, for example I have module that saves current RawUrl in BeginRequest :

      public class PlainModule : IHttpModule
      {
        private HttpApplication app = null;    
        public string CurrentRequestUrl;
    
        public void Init(HttpApplication Context)
        {
          this.app = Context;
          Context.BeginRequest += new System.EventHandler(Begin);
        }
    
        public void Dispose()
        {
        }
    
        private void Begin(Object Sender, EventArgs e)
        {
          this.CurrentRequestUrl = this.app.Request.RawUrl;
        }
      }
    

    Of course you have to register your module in web.config :

      <system.web>
        <httpModules>
          <add name="PlainModule" type="WebApplication1.PlainModule, WebApplication1"/>
        </httpModules>
      </system.web>
    

    and then you can get module instance using name registered in web config, like this :

    protected void Page_Load(object sender, EventArgs e)
    {
      PlainModule pm = (PlainModule)HttpContext.Current.ApplicationInstance.Modules["PlainModule"];
      Response.Write("Current request URL : "  + pm.CurrentRequestUrl);
    }