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?开发者_StackOverflow中文版
Thanks! :)
You should not redirect from your OnAuthorization function but rather set the Result parameter from the filterContext as such :
filterContext.Result == new RedirectToRouteResult(new RouteValueDictionary {
{
"controller",
"Utilisateurs"
},
{
"action",
"Connexion"
},
{
"ReturnUrl",
filterContext.HttpContext.Request.RawUrl
}
});
精彩评论