您的位置:首页 > 编程语言 > C#

C#一般处理程序设置和读取session(session报错“未将对象引用设置到对象的实例”解决)

2016-04-16 15:15 721 查看
做自己的毕业设计登陆模块时,用到了session和cookie。在一般处理程序中处理session,一直报错。最后找到问题原因是需要调用
irequiressessionstate接口。

在ashx文件中,设置session直接用HttpContext.Current.Session["UserCode"] = usercode会报“未将对象引用设置到对象的实例”错误。搜索到很多资料说没有判断session对象是否存在,我是设置session对象,自然不是因为这个错误的。通过查找资料看到http://www.cnblogs.com/tonysuen/archive/2010/12/07/1899595.html   的博文,修改了代码,调用了接口,完成了登陆功能。

ashx文件中使用session需要using System.Web.SessionState;

根据需要调用IRequiresSessionState接口(读写)或者IReadOnlySessionState(只读)
using System;
using System.Collections.Generic;
using System.Web;
using DMS;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Web.SessionState;

// 调用IRequiresSessionState接口
public class login1 : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string usercode = context.Request["usercode"].ToString();
string type = context.Request["type"].ToString();
string fun = context.Request["fun"].ToString();
switch (fun)
{
case "checkUser":
string pwd = context.Request["pwd"].ToString();
checkUser(type, usercode, pwd, context);
break;
default:
break;
}
}

//验证用户信息(用户名和密码)
public void checkUser(string type, string usercode, string pwd, HttpContext context)
{
string res = "";
string sql = @"select count(1) from " + type + " t where t.usercode='" + usercode + "'
and t.userpwd ='" + pwd + "' ";
try
{
DataTable dt = sqlCon.getDt(sql);
string count = dt.Rows[0][0].ToString();
if (count == "1")
{
//如果有数据,则设置session
HttpContext.Current.Session["UserCode"] = usercode;
HttpContext.Current.Session["type"] = type;
HttpContext.Current.Session["UserPwd"] = pwd;
res = "ok";
}
else
{
res = "er";
}
}
catch (Exception e)
{
res = "checkUser__" + e.ToString();
}
finally
{
context.Response.Write(res);
}
}
}

用作自己积累,同时希望能对碰到同样问题的同志有一些参考作用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: