I am looking for a way to pass data between events of HttpApplication. For example, I have the following code in my HTTP module:
public void Init(HttpApplication context)
{
context.BeginRequest += DoFoo;
context.EndRequest += DoBar;
}
I want to save some data during BeginRequest
event in the DoFoo
method and access it later during the EndRequest
event in the DoBar
method.
As far as I am aware, Session
is not available at this point yet. Is there a way to store the data between events so that it is:
Update:
Is it possible to use HTTP module instance variables to achieve this? Is there any risk that the data stored in these variables would be accessible outside the current request?
As per John Wo's comment under my question, my problem was solved by using HttpContext.Items
. This is the link to the article provided by John .
Example of using HttpContext.Items
:
public void Init(HttpApplication context)
{
context.BeginRequest += DoFoo;
context.EndRequest += DoBar;
}
private void DoFoo(Object sender, EventArgs e)
{
HttpApplication httpApplication = (HttpApplication)sender;
httpApplication.Context.Items.Add("MyFlag", true);
}
private void DoBar(Object sender, EventArgs e)
{
HttpApplication httpApplication = (HttpApplication)sender;
if(httpApplication.Context.Items.Contains("MyFlag") && (bool)contextItems["MyFlag"] == true)
{
//Do stuff...
}
}
I'm not exactly sure when Session is first available but I'm able to access it with this little-known event in Global.asax, fwiw:
// This event is executed for every page request
// and is run before the PreInit event.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
Session["ok"] = "OK";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.