MVC3 Redirect after login
Been trying to put together an mvc login page that will redirect back to the original page that required authorization based on other stack overflow posts.
Redirect with
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "login" },
{"ReturnUrl", filterContext.HttpContext.Request.RawUrl},
{ "controller", "mycontroller" }
});
}
login page view has
@Html.Hidden("returnUrl", ViewContext.HttpContext.Request.Params["returnurl"])
located inside the form. I originally used ViewContext.HttpContext.Request.Url.PathAndQuery based on another forum post, but that included the entire url.
Inside controller I have
开发者_运维百科[HttpPost]
public ActionResult Login(MyModel model)
{
if (loginisValid)
return Redirect(model.ReturnUrl);
else
return View();
}
but that does nothing but return the orignal page even though it's hitting the Redirect. I've also tried RedirectToAction and RedirectToRoute, but those give errors. I'm testing this on my index page which is at localhost/admin/mycontroller. So model.ReturnUrl currently contains "/admin/mycontroller". What should I be changing to make this work?
It turned out all this code was correct. However, I didn't put
[RequireHttps(Order=0)]
on top of my controller so it never stored cookies correctly and after redirecting back to my index page it was failing authorization again.
I'm using Forms Authentication but I use this line..
Response.Redirect(!string.IsNullOrEmpty(returnUrl) ? returnUrl : FormsAuthentication.DefaultUrl);
精彩评论