2013-10-15 34 views
2

基於默認的Identity框架,我想在用戶登錄到應用程序時設置會話變量。如何設置會話變量,當用戶在asp中使用'記住我'cookie登錄mvc

這非常適用:

[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
{ 
    if(ModelState.IsValid) 
    { 
     // Validate the password 
     IdentityResult result = await IdentityManager.Authentication.CheckPasswordAndSignInAsync(AuthenticationManager, model.UserName, model.Password, model.RememberMe); 

     if(result.Success) 
     { 
      //save display name in session view 
      SiteUser user = await _siteDbContext.Users.SingleOrDefaultAsync(u => u.UserName == model.UserName); 
      Session["displayName"] = user.DisplayName; 

      return RedirectToLocal(returnUrl); 
     } 

     AddErrors(result); 
    } 

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 

而它與這條線顯示在網站的最上面一欄:

@Html.ActionLink(Session["displayName"].ToString(), "Manage", "Account", null) 

然而,當我登錄與「記住我」選項選中,關閉瀏覽器並重新啓動它,會話變量不會被設置,頁面會拋出一個空引用異常。

挖掘一點,它看起來好像將/Account/Login操作設置爲默認登錄路徑,但它永遠不會被cookie身份驗證調用。

我該如何才能在身份驗證過程的中間或之後 - 設置我的會話變量?

+0

顯然Session對象不設置,因爲登錄行動得到由認證系統規避。我可以編輯它,還是必須進行檢查並在每個控制器中設置Session值? –

+0

Aaaaand我無法在用戶發出的第一個請求中引用Session對象。有沒有辦法強制創建Session對象? –

回答

-1

使用formauthentication Httpcookies。 另請檢查登錄操作是否存在Cookie。

如果存在,則從cookie中提取用戶名並再次提出會話。

爲formauthentication Httpcookies click here

+1

因此,我必須用手工製作的系統替換內置系統,然後呢?因爲在登錄操作中設置斷點在使用cookie登錄時根本不會觸發。 –

相關問題