2014-08-27 61 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

相关问题