views:

50

answers:

5

I am writing an asp.net HTTP module which needs to read configuration data once from a local file (say config.xml stored in application root directory) and then based on configuration perform some processing on incoming requests.

Since there is no Application_Start/Application_init hooking available in Asp.NET modules, what would be the best way to handle the scenario. I am trying to avoid reading configuration file each time a request comes. Ideally, I want to read the config file when application starts.

I need to code this in http module only and do not want to use Global.asax

A: 

Not sure if this would work, but you might be able to implement this in the module's init method.

Chris Pebble
I just tried it. It seems that that variables/objects etc in Init method are not available in HTTPmodule "hookable" events like Application_BeginRequest etc
Gaurav Kumar
A: 

In the init method of your httpmodule you can hook up to the event in the context.

For example :

public void Init(HttpApplication context)
    {

        context.PostRequestHandlerExecute += (sender, e) =>
        {
            Page p = context.Context.Handler as Page;
            if (p != null)
            {
            ///Code here    
            }
        };
    }
Richard Friend
just noticed there is no start event to hook upto, why not just populate the data in the init method of your http module...
Richard Friend
A: 
public SomeHttpModule : IHttpModule
{    
    private static readonly Configuration Configuration = 
            ConigurationReader.Read();    
}
Chris Marisic
A: 

static variable did the trick. here is the code if someone is interested -

static string test; 
        public void Init(HttpApplication application)
        {


            application.BeginRequest +=(new EventHandler(this.Application_BeginRequest));
            test = "hi"; 
            application.EndRequest +=(new EventHandler(this.Application_EndRequest));


        }
       private void Application_BeginRequest(Object source,EventArgs e)
        {
            {
                HttpApplication application = (HttpApplication)source ;
                HttpContext context = application.Context;
                context.Response.Write(test);
            }


        }
Gaurav Kumar
+1  A: 

I'd go for a simple property, something like this ...

public MyConfig Config
{
    get
    {
        MyConfig _config = Application["MyConfig"] as MyConfig;
        if (_config == null)
        {
            _config = new MyConfig(...);
            Application["MyConfig"] = _config;
        }
        return _config;
    }
}

that way you just access whatever you need from Config via the property ...

int someValue = Config.SomeValue;

and it's loaded into the application object if it hasn't been already

If you need the config on a per-user basis rather than globally, then just use Session["MyConfig"] instead of Application["MyConfig"]

Antony Scott