I. Problem description:
Recently, a specific request (. report) for response interfaces, of course, IHttpHandler is implemented for processing. To implement the IHttpHandler interface, you must implement the two methods: ProcessRequest (HttpContext context) and IsRunable (), we can see that there is an HttpContext input parameter in ProcessRequest (HttpContext context), so that we can use all the server objects through this. However, the problem arises. In this custom HTTP Response Processing class, both Request and Response can be referenced and used through HttpContext, but Session does not work, there is always an error where the object is not referenced!
Ii. solution:
You can use the SESSION method in custom HTTPHANDLER to query information online!
1. First reference the namespace System. Web. SessionState,
2. If you want to read the Session content in HttpHandler, you must implement the IReadOnlySessionState interface in the IHttpHandler class at the same time.
3. If you want to read and write Session content in HttpHandler, You need to implement IRequiresSessionState at the same time in the class implementing IHttpHandler.
In this way, the Session can be used normally in the Custom HttpHandler.
Iii. Code Demonstration:
1. cs files on the front-end page
Public partial class TestPage: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Protected void BtnUpLoad_Click (object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument ();
Doc. Load (TemplateUpload. FileContent );
Session ["upLoadXmlDoc"] = doc;
String url = "test. report ";
Response. Redirect (url );
}
}
2. Implement the IHttpHandler HttpHandler class to process test. report
Public class myHttpHandler: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
String className = businessConfig. Business [context. Request. Path];
// An error will be reported in this row, prompting: Object reference not set to an instance of an object.
// Add monitoring and learn that context. Session is null
XmlDocument doc = context. Session ["upLoadXmlDoc"]
}
// Override the IsReusable property.
Public bool IsReusable
{
Get {return true ;}
}
}
3. solution:
Let myHttpHandler implement IRequiresSessionState and then OK.
Public class myHttpHandler: IHttpHandler, IRequiresSessionState
{
Public void ProcessRequest (HttpContext context)
{
String className = businessConfig. Business [context. Request. Path];
XmlDocument doc = context. Session ["upLoadXmlDoc"]
Www.2cto.com
}
// Override the IsReusable property.
Public bool IsReusable
{
Get {return true ;}
}
}
From: read blog