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
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"]
Not sure if this would work, but you might be able to implement this in the module's init method.
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
}
};
}
public SomeHttpModule : IHttpModule
{
private static readonly Configuration Configuration =
ConigurationReader.Read();
}
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);
}
}
来源:https://stackoverflow.com/questions/3119034/how-to-handle-application-start-event-in-asp-net-module