今天写程序得时候遇到了一个问题:ajax在对ashx进行请求时如果按照 context.Request方式直接来获取值得话获取到得是空值,因此去网上搜了一下问题。现记录如下:
ashx获取session值:
1.首先添加引用:using System.Web.SessionState;
2.我们得一般处理程序类要继承IRequiresSessionState接口
3.对session值判断是否为null
4.使用context.session["***"] 得到对应得session值
下面写一个例子测试一下:
html代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试界面</title>
<script src="javascript/jquery-1.11.1.min.js"></script>
<style>
</style>
<script>
//测试ajax向后台获取信息
function getinfo() {
$.ajax({
url: "ashx/Handler1.ashx?action=get",
dataType: "text",
success: function (data) {
alert(data);
},
})
}
function setsession() {
$.ajax({
url: "ashx/Handler1.ashx?action=set",
})
}
window.onload = function () {
setsession();
getinfo();
}
</script>
</head>
<body>
<div id="test">
</div>
</body>
</html>
ashx代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace Biobase_BigData.ashx
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler, IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = "";
if (context.Request.QueryString["action"] != null)
{
action = context.Request.QueryString["action"].ToString();
}
switch (action)
{
case "get":
string session = "";
if(context.Session["name"]!=null){
session = context.Session["name"].ToString();
}
context.Response.Write(session);
break;
case "set":
context.Session["name"] = "ceshi";
break;
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}
运行结果显示: