I'm working on an mvc .net application and I'm using forms authentication. I want to redirect user to the page he requested after he gets authenticated. Any help would be appreciated.
问题:
回答1:
If you create an ASP.NET MVC 3 or 4 Internet Application project, it'll have a complete example of how to use return url's when authenticating.
When you add the AuthorizeAttribute to a controller to force authentication, it'll redirect the user to your Login method, and automatically append the returnUrl parameter. From there, you need to keep track of it as you show your login form:
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
and then add it to your login form's route collection:
@*//ReSharper disable RedundantAnonymousTypePropertyName*@
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@*//ReSharper restore RedundantAnonymousTypePropertyName*@
}
Once the user submits the login, assuming they authenticate properly, you'll just redirect to returnUrl:
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
return RedirectToLocal(returnUrl);
}
The hardest part is keeping track of the ReturnUrl through the GET/POST sequence.
If you want to see how the AuthorizeAttribute works, this StackOverflow post shows setting returnUrl with the original request.
You also need to make sure you validate returnUrl really is a local url, or you become vulnerable to open redirection attacks. RedirectToLocal() is a helper method from the MVC 4 Internet Application template that does this validation:
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}