.net 在FormsAuthentication.SignOut()之后继续执行MVC控制器
我将所有会话保存在数据库中。让我们假设此会话丢失在数据库中,而不是cookie中 在OnAuthorization(AuthorizationContext filterContext)中,我根据会话id从数据库检索用户对象.net 在FormsAuthentication.SignOut()之后继续执行MVC控制器,.net,model-view-controller,session,authentication,controller,.net,Model View Controller,Session,Authentication,Controller,我将所有会话保存在数据库中。让我们假设此会话丢失在数据库中,而不是cookie中 在OnAuthorization(AuthorizationContext filterContext)中,我根据会话id从数据库检索用户对象 if (HttpContext.User.Identity.IsAuthenticated) { //Gets user data from DB. var user = userRepos.GetUser(HttpContext.User.Identity
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
如何避免这个错误
谢谢!:) 您不应该从OnAuthorization函数重定向,而应该从filterContext设置结果参数,如下所示:
filterContext.Result == new RedirectToRouteResult(new RouteValueDictionary {
{
"controller",
"Utilisateurs"
},
{
"action",
"Connexion"
},
{
"ReturnUrl",
filterContext.HttpContext.Request.RawUrl
}
});
它工作得很好!非常感谢。但为什么从授权中使用重定向是不对的呢。这两种方法的区别是什么?因为您不应该直接管理重定向,而应该向mvc指示您要重定向,从而允许它正确管理重定向。你的“响应。重定向”有点像在中间停止进程。