FormsAuthentication.SignOut() 之后继续执行 MVC 控制器
我将所有会话保存在数据库中。让我们假设该会话在数据库中丢失,而不是在 cookie 中丢失。
在 OnAuthorization(AuthorizationContext filterContext) 中,我根据会话 ID 从数据库检索用户对象。
if (HttpContext.User.Identity.IsAuthenticated)
{
//Gets user data from DB.
var user = userRepos.GetUser(HttpContext.User.Identity.Name);
if (user != null)
{
CurrentUser = user;
Thread.CurrentPrincipal = HttpContext.User = new DibPrincipal(user);
return;
}
else
{
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect(FormsAuthentication.LoginUrl, true);
}
}
}
想象一下,用户调用了控制器 GetDocuments,但他被重定向到 FormsAuthentication.LoginUrl。它有效,用户被重定向,但我收到异常,该异常显示 GetDocument 控制器中的错误,因为 CurrentUser 不存在。因此,.net 即使在重定向后也会尝试调用 GetDocuments。
如何避免这个错误呢?
谢谢! :)
I save all session in the database. Lets imagine that this session was lost in the database, not in the cookies.
In OnAuthorization(AuthorizationContext filterContext) I retrieve user object from database base on the session id.
if (HttpContext.User.Identity.IsAuthenticated)
{
//Gets user data from DB.
var user = userRepos.GetUser(HttpContext.User.Identity.Name);
if (user != null)
{
CurrentUser = user;
Thread.CurrentPrincipal = HttpContext.User = new DibPrincipal(user);
return;
}
else
{
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect(FormsAuthentication.LoginUrl, true);
}
}
}
Imagine that user called a controller GetDocuments, but he was redirected to FormsAuthentication.LoginUrl. It works, user is been redirected, but I get en exception which shows an error in GetDocument controller, because CurrentUser does not exist. So .net trying to call GetDocuments even after redirecting.
How to avoid this error?
Thanks! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应该从 OnAuthorization 函数重定向,而应该从 filterContext 设置 Result 参数,如下所示:
You should not redirect from your OnAuthorization function but rather set the Result parameter from the filterContext as such :