解决ashx文件下的Session“未将对象引用设置到对象的实例”

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using PPT_DAL;
 6 namespace PPT_Web.tool
 7 {
 8     /// <summary>
 9     /// Login 的摘要说明
10     /// </summary>
11     public class Login : IHttpHandler
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/html";
17             string lo_usm = context.Request.Params["lo_usm"];
18             string lo_pwd = context.Request.Params["lo_pwd"];
19             UserEntity userModel = PPT_BLL.UserManager.Login(lo_usm,lo_pwd);
20             if (userModel != null)
21             {
22                 context.Session["UserId"] = userModel.USR_ID;
23                 context.Response.Write("{'result':'1'}");
24             }
25             else
26             {
27                 context.Response.Write("{'result':'0'}");
28             }
29         }
30 
31         public bool IsReusable
32         {
33             get
34             {
35                 return false;
36             }
37         }
38     }
39 }

问题:

   如题所示,在一般处理程序文件,即ashx文件下调用Session["UserId"],当调试的时候会显示“未将对象实例化的”的错误

解决方法:

  将该类实现“IRequiresSessionState”的接口即可,而此接口在System.Web.SessionState命名空间下,所以要在上面添加一句:using System.Web.SessionState;

  最终实现代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using PPT_DAL;
 6 using System.Web.SessionState;
 7 namespace PPT_Web.tool
 8 {
 9     /// <summary>
10     /// Login 的摘要说明
11     /// </summary>
12     public class Login : IHttpHandler, IRequiresSessionState
13     {
14 
15         public void ProcessRequest(HttpContext context)
16         {
17             context.Response.ContentType = "text/html";
18             string lo_usm = context.Request.Params["lo_usm"];
19             string lo_pwd = context.Request.Params["lo_pwd"];
20             UserEntity userModel = PPT_BLL.UserManager.Login(lo_usm,lo_pwd);
21             if (userModel != null)
22             {
23                 context.Session["UserId"] = userModel.USR_ID;
24                 context.Response.Write("{'result':'1'}");
25             }
26             else
27             {
28                 context.Response.Write("{'result':'0'}");
29             }
30         }
31 
32         public bool IsReusable
33         {
34             get
35             {
36                 return false;
37             }
38         }
39     }
40 }
原文地址:https://www.cnblogs.com/huanbia/p/3331116.html