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

时间:2023-12-29 11:21:26
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PPT_DAL;
namespace PPT_Web.tool
{
/// <summary>
/// Login 的摘要说明
/// </summary>
public class Login : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string lo_usm = context.Request.Params["lo_usm"];
string lo_pwd = context.Request.Params["lo_pwd"];
UserEntity userModel = PPT_BLL.UserManager.Login(lo_usm,lo_pwd);
if (userModel != null)
{
context.Session["UserId"] = userModel.USR_ID;
context.Response.Write("{'result':'1'}");
}
else
{
context.Response.Write("{'result':'0'}");
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}

问题:

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

解决方法:

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

  最终实现代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PPT_DAL;
using System.Web.SessionState;
namespace PPT_Web.tool
{
/// <summary>
/// Login 的摘要说明
/// </summary>
public class Login : IHttpHandler, IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string lo_usm = context.Request.Params["lo_usm"];
string lo_pwd = context.Request.Params["lo_pwd"];
UserEntity userModel = PPT_BLL.UserManager.Login(lo_usm,lo_pwd);
if (userModel != null)
{
context.Session["UserId"] = userModel.USR_ID;
context.Response.Write("{'result':'1'}");
}
else
{
context.Response.Write("{'result':'0'}");
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}