2017-10-16 51 views
0

我的应用程序中有以下代码。 Constants.SESSION_USER是一个字符串值。在mvc中通过Ajax访问时,会话为空

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;   
    } 
} 

当此GetSession()设置用户会话方法通过ajax请求调用,this.UserAccountnull

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

+2

您的AJAX请求不会发送会话cookie。如果您不想要安全问题,请不要重新进行身份验证。 – CodeCaster

+0

@CodeCaster:会话cookie自动发送到ajax请求中,不是吗? –

+0

如果它是一个HttpOnly cookie,则不是。我们真的不能说这是因为它都是定制的。 – CodeCaster

回答

0

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