2017-10-16 97 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未在瀏覽器中設置)。當我使用不同的瀏覽器時,它工作。似乎也沒有代碼問題。