要从自定义处理程序中访问页面中设置的变量,可以使用HttpContext.Current.Items集合。此集合可在整个请求过程中共享,因此您可以在IHttpModule中将其用作共享状态存储。
以下是如何在自定义处理程序中访问在页面中设置的变量的示例:
在页面中设置变量:
void Page_Load(object sender, EventArgs e) { HttpContext.Current.Items["myVariable"] = "Hello World"; }
在自定义处理程序中访问变量:
public class CustomHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string myVariable = context.Items["myVariable"] as string; if (!string.IsNullOrEmpty(myVariable)) { // Do something with myVariable } } }
然后,您可以在IHttpModule的BeginRequest事件处理程序中访问变量:
public class CustomHttpModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); }
void context_BeginRequest(object sender, EventArgs e)
{
string myVariable = HttpContext.Current.Items["myVariable"] as string;
if (!string.IsNullOrEmpty(myVariable))
{
// Do something with myVariable
}
}
public void Dispose() { }
}