在 mvc 中通过 Ajax 访问时会话为空

Session is null when accessed via Ajax in mvc

我的应用程序中有以下代码。 Constants.SESSION_USER 是一个字符串值。

public class BaseController : Controller
{
    public Account UserAccount
    {
        get
        {
            if (Session[Constants.SESSION_USER] is User)
            {
                return Session[Constants.SESSION_USER] as User;
            }
            return null;
        }
        set
        {
            Session[Constants.SESSION_USER]     = value;
        }
    }
}

以下是我将用户设置为 Session

public class AccountController : BaseController
{
    [HttpPost]
    public JsonResult Login(LoginViewModel loginView)
    {
        User loggedInAccount = null;    
        // some logic to validate the user

        // if no validation issues
        User loggedAccount = new User(loginView.ID);
        //set the logged account into the session
        this.UserAccount = loggedAccount;
    }
}

在下面的代码中,我正在访问我之前在 AccountController

中设置的用户会话
[HttpPost]
public JsonResult GetSession()
{
   User loggedInAccount = null;

   if (this.UserAccount != null) // this.UserAccount is null
   {
      //get the user from the session
      loggedInAccount = this.UserAccount;         
   }
}

当通过 ajax 请求调用此 GetSession() 方法时,this.UserAccountnull

我有点困惑,因为这有时有效,有时无效。这里有什么问题?

更新:这个问题似乎是由浏览器引起的。浏览器中的某些设置可能导致会话为空(ASP.NET SessionId 未在浏览器中设置)。当我使用不同的浏览器时,它起作用了。似乎也没有代码问题。