IHttpHandler Session

  今天在工作编写代码时,在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问题

你可能感兴趣的:(session)