登陆模块时,用到了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);
}
}
}

posted on 2017-10-13 10:27  田坤坤  阅读(1364)  评论(0编辑  收藏  举报