在一般处理程序中使用Session取不到值的解决方法
我们经常,通过session判定用户是否登录。还有一些临时的、重要的数据也尝尝存放在Session中。
在页面我们很容易的得到Session的值,但在类中就会遇到一些问题。也知道通过下面的方法得到。
System.Web.HttpContext.Current.Session["chkCode"];
但是今天此种方法也失灵了。在做一个项目的登录功能时,需要实现IHttpHandler,同时也需要用到验证码。但是在这个类中怎么也不能找到Session的值,曝出
System.Web.HttpContext.Current.Session为null
为什么得到的Session会是空呢?想了好久也没想通。找了好久,才找到了高人的指点,问题得到了解决。
解决方法:
在实现IHttpHandler的同时,也要实现IRequiresSessionState接口,其命名空间为:System.Web.SessionState。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace PlatformV2_Web.DaSai.BankSecuritiesInsuranceDasai.ashx
{
/// <summary>
/// index 的摘要说明
/// </summary>
public class index : IHttpHandler,IRequiresSessionState //这里要实现IRequiresSessionState接口,在IHttpHandler后面用逗号隔开加上 IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string userName = context.Request.Form["userName"];
string pwd = context.Request.Form["password"];
string cord = context.Request.Form["VCode"];
if (context.Session["chkCode"] != null)
{
if (context.Session["chkCode"].ToString() == cord)
{
if (userName == "admin" && pwd == "admin")
{
context.Response.Write("登录成功!");
}
else
{
context.Response.Write("登录失败!用户名或者密码错误");
}
}
else
{
context.Response.Write("验证码错误!");
}
}
//context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
继续追踪:
为什么要实现这个接口呢?这个接口是做什么用的呢?继续追踪,MSDN给了最终解释。
IRequiresSessionState
指定目标 HTTP 处理程序需要对会话状态值具有读写访问权。这是一个标记接口,没有任何方法。
作用:
在自定义 HTTP 处理程序中实现 IRequiresSessionState 接口,以确定处理程序是否需要对会话状态值具有读写访问权
所以记得哦,如果在自定义HTTP处理程序中,要访问Session,记得一定要实现这个接口哦。不然你一直取不到值...

浙公网安备 33010602011771号