今天在工作編寫代碼時,在IHttpHandler的父類中使用了Session,在后台代碼中調用該Session,但是拋出異常說該Session是Null,在網上查詢相關資料說必須繼承借口:IReadOnlySessionState 或 IRequiresSessionState,必須應用System.Web.SessionState命名空間
IHttpHandler:
// Summary:
// Defines the contract that ASP.NET implements to synchronously process HTTP
// Web requests using custom HTTP handlers.
public interface IHttpHandler
{
// Summary:
// Gets a value indicating whether another request can use the System.Web.IHttpHandler
// instance.
//
// Returns:
// true if the System.Web.IHttpHandler instance is reusable; otherwise, false.
bool IsReusable { get; }
// Summary:
// Enables processing of HTTP Web requests by a custom HttpHandler that implements
// the System.Web.IHttpHandler interface.
//
// Parameters:
// context:
// An System.Web.HttpContext object that provides references to the intrinsic
// server objects (for example, Request, Response, Session, and Server) used
// to service HTTP requests.
void ProcessRequest(HttpContext context);
}
IReadOnlySessionState:表示Http handler能夠讀取Session的值
// Summary:
// Specifies that the target HTTP handler requires only read access to session-state
// values. This is a marker interface and has no methods.
public interface IReadOnlySessionState : IRequiresSessionState
{
}
IRequiresSessionState:表示Http handler能夠讀寫Session的值
// Summary:
// Specifies that the target HTTP handler requires read and write access to
// session-state values. This is a marker interface and has no methods.
public interface IRequiresSessionState
{
}
將繼承IHttpHandler的類同時實現IRequiresSessionState 或 IReadOnlySessionState,即可使用Session,如下所示:
public class TestHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Session["TestSession = "TestSession";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
即可解決IHttpHandler不能使用Session問題
