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
action方法中的立即返回值设法解决了该错误,但是我想知道为什么会发生此错误。
因为在第一次调用用户/发送的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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句