在.aspx.cs页中读写Session都是Session["***"]就可以获取或者写入。但是在一般处理程序也就是ashx页面中,再这样写的话,就会为null,
解决办法是先要添加命名空间using System.Web.SessionState;
然后再继承接口
其中:System.Web.SessionState.IReadOnlySessionState为只读会话的接口
而:System.Web.SessionState.IRequiresSessionState 为可读可写会话的接口
根据自身需要来继承。
下面我们就来上vs代码
#region 用户对象
public class Users {
public string UserOpenId { get; set; }
public string UserName { get; set; }
public string UserImgUrl { get; set; }
}
#endregion
#region 服务
public static string SetSession(HttpContext context)
{
string UserOpenId = context.Request.Form["UserOpenId"].ToString();
string UserName = context.Request.Form["UserName"].ToString();
string UserImgUrl = context.Request.Form["UserImgUrl"].ToString();
Users UserObj = new Users();
UserObj.UserOpenId = UserOpenId;
UserObj.UserName = UserName;
UserObj.UserImgUrl = UserImgUrl;
context.Session["UserObj"] = UserObj;
return JsonConvert.SerializeObject(new { OK = "设置成功" });
}
public static string GetSession(HttpContext context) {
Users GetUserObj = new Users();
GetUserObj = context.Session["UserObj"] as Users;
if (GetUserObj == null)
{
string GetUserObjs = "没有数据";
return JsonConvert.SerializeObject(new { OK = "获取成功但是没数据", Data = GetUserObjs });
}
else {
return JsonConvert.SerializeObject(new { OK = "获取成功", Data = GetUserObj });
}
}
#endregion
在这里引用了可存可取的session极致 可以完美解决微信的存不住数据的问题。可以看到返回数据为json格式的需要引入
using Newtonsoft.Json;
在存取的时候需要用context 的。而不能用直接session 存取。因为ashx 是把数据放到context 对象中返回的。
现在看下html5调取方式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
<style type="text/css" >
div {
width:200px;
height:200px;
border:1px solid red;
}
</style>
<script src="Js/jquery-1.12.4.min.js" type="text/javascript"></script>
<script>
function OpenSet() {
var UserOpenId = "001";
var UserName = "明码";
var UserImgUrl = "1.jpg";
$.ajax({
url: "SessionServices.ashx",
type: "POST",
dataType: "json",
data: {
"ControllerName": "Session",
"ActionName": "Set",
"UserOpenId": UserOpenId,
"UserName": UserName,
"UserImgUrl": UserImgUrl
},
success: function (data) {
if (data.OK) {
alert(data.OK);
}
else {
alert(data.Err);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert('cc');
console.log("访问接口出错");
}
});
}
function OpenGet() {
$.ajax({
url: "SessionServices.ashx",
type: "POST",
dataType: "json",
data: {
"ControllerName": "Session",
"ActionName": "Get"
},
success: function (data) {
if (data.OK) {
alert(data.OK + "--" + data.Data.UserOpenId + "--" + data.Data.UserName + "--" + data.Data.UserImgUrl);
console.log(data.OK);
console.log(data.Data.UserOpenId);
console.log(data.Data.UserName);
console.log(data.Data.UserImgUrl);
}
else {
console.log(data.Err);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert('cc');
console.log("访问接口出错");
}
});
}
</script>
</head>
<body>
<div onclick="OpenSet();" >设置</div>
<div onclick="OpenGet();" >获取</div>
</body>
</html>