C# session使用方法

Global.asax.cs 里面添加

        public override void Init()
        {
            //注册事件
            this.AuthenticateRequest += WebApiApplication_AuthenticateRequest;
            base.Init();
        }
        void WebApiApplication_AuthenticateRequest(object sender, EventArgs e)
        {
            //启用 webapi 支持session 会话
            HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }
        protected void Session_Start(object sender, EventArgs e) { string sessionId = Session.SessionID; }

使用

HttpContext.Current.Session["demo"] ="demo"

每次请求接口时回会产生一个sessionid 存在Cookie 里面,请求时必须保证sessionid 一致

但是,微信小程序不能保存Cookie,导致每次wx.request到服务端都会创建一个新的会话,小程序端就不能保持登录状态了

简单的处理方法如下:

1. 把服务端response的Set-Cookie中的值保存到Storage中

wx.request({
    url: path,
    method:method,
    header: header,
    data:data,
    success:function(res){
        if(res && res.header && res.header['Set-Cookie']){
            wx.setStorageSync('cookieKey', res.header['Set-Cookie']);//保存Cookie到Storage
          }
},
    fail:fail
  })

2. wx.request再从Storage中取出Cookie,封装到header中

  let cookie = wx.getStorageSync('cookieKey');
  let path=conf.baseurl+url;
  let header = { };
  if(cookie){
    header.Cookie=cookie;
  }
  
  wx.request({
    url: path,
    method:method,
    header: header,
    data:data,
    success:success,
    fail:fail

})

 

你可能感兴趣的:(C# session使用方法)