2014-08-27 64 views
2
public ActionResult Login(CredentialsModel model) 
{ 
    authenticator.Authenticate(model.Username, model.Password); 

    if (authenticator.Authenticated) 
    { 
     return Redirect(); 
    } 
} 

... 

public class Authenticator : IAuthenticator 
{ 
    public bool Authenticated 
    { 
     get { return HttpContext.Current.User.Identity.IsAuthenticated; } 
    } 

    public void Authenticate(string username, string password) 
    { 
     var authenticated = FormsAuthentication.Authenticate(username, password); 
     if (authenticated) 
      FormsAuthentication.SetAuthCookie(username, false); 
    } 

    public void Logout() 
    { 
     FormsAuthentication.SignOut(); 
    } 
} 

當上述操作方法向Authenticate方法提供某些有效憑據時,Authenticated屬性返回false,這顯然是錯誤的。爲什麼用戶必須輸入兩次正確的憑證?

當動作方法提供第二個時間的某些憑據時,Authenticated屬性返回true。

我懷疑這與事實的上下文沒有立即更新。我實際上設法通過在動作方法中使用立即返回值FormsAuthentication.Authenticate來解決此錯誤,但我想知道爲什麼發生此錯誤。

回答

1

因爲在第一個呼叫用戶發送的HTTP上下文中是而不是已通過身份驗證(但在後續調用之後它會正確地發送)。在此行之後:

var authenticated = FormsAuthentication.Authenticate(username, password); 

您可能會看到那authenticated != Authenticated。爲什麼?從MSDN

[HttpContext]封裝有關單個HTTP請求的所有特定於HTTP的信息。

這意味着它可以在要求(你的輸入),不能在響應或未來狀態(您的輸出)。如果您在控制器的方法內執行SignOut(),您還會看到HttpContext.Current.User.Identity.IsAuthenticated仍然是true

你可以做的是爲Authenticate()添加一個布爾返回值:

public bool Authenticate(string username, string password) 
{ 
    var authenticated = FormsAuthentication.Authenticate(username, password); 
    if (authenticated) 
     FormsAuthentication.SetAuthCookie(username, false); 

    return authenticated: 
} 

在控制器更改然後代碼:

if (authenticator.Authenticate(model.Username, model.Password)) 
{ 
    return Redirect(); 
} 
+0

這個答案是不是所有的幫助我很抱歉。請詳細說明第一段。代碼示例對我也沒有幫助,因爲我已經解決了像我在問題中提到的問題:c – 2014-08-27 11:52:42

+0

我用一些代碼更新了答案。簡而言之:HttpContext引用HTTP **請求**。在這種情況下,用戶WAS未經過身份驗證(並且在處理他的請求時HttpContext不會更改,因爲您正在處理響應)。 – 2014-08-27 11:54:19

+0

在那裏,我們去配偶。發現。謝謝。 – 2014-08-27 11:57:59

相關問題