0

我想做的是在 API 中使用 HttpContext.Session

在同一个 WebApi Controller 但不同的操作中。

$.ajax({
url:baseAppUrl+"api/login",
type:"post",
data:{
action:"sms",
username:"",///mobile phone
},
success:function(ret,err){

}

它会给我一个代码,然后使用该代码登录。

但是在ajax再次发送reqeust之后我无法获得HttpContext.Session。

我正在使用 .net 核心 3.1

if (action.Equals("sms"))
        {
            if (string.IsNullOrEmpty(username))
            {
                return Json(new { Ok = false, Message = "parameter is null" });
            }
            Random rnd = new Random();
            var verifyCode = rnd.Next(111111, 999999).ToString();
            HttpContext.Session.SetString("code", verifyCode);
            return Json(new { Ok = true, Message = verifyCode });
        }

并在登录操作中:

if (action.Equals("mobileLogin"))
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(code))
            {
                return Json(new { Ok = false, Message = "paremeter is null" });
            }
            var userCode = HttpContext.Session.GetString("code"); //the userCode will be null.
            if (!string.IsNullOrEmpty(userCode))
            {
                ////.....
            }
}

但是有了邮递员,一切就都解决了。

为什么?

4

1 回答 1

0

Startup.cs中,确保将以下内容添加到ConfigureServicesConfigure方法中

public void ConfigureServices(IServiceCollection services)  
{
    ...  
    services.AddSession(options => {  
        options.IdleTimeout = TimeSpan.FromMinutes(20);//You can set Time   
    });
    ...  
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseSession();
    ...
}

请同时检查浏览器是否接收到会话 cookie。在 Chrome 中:

  1. 单击 URL 栏中的锁定图标
  2. 点击 Cookie
  3. 看看有没有cookie .AspNetCore.Session,如下图

在此处输入图像描述

如果 cookie 在那里,问题可能不在于处理会话数据,而在于其他地方。

于 2020-03-26T08:47:36.313 回答