【发布时间】:2012-10-30 19:08:51
【问题描述】:
我正在开发一个 mvc .net 应用程序,并且我正在使用表单身份验证。我想在用户通过身份验证后将用户重定向到他请求的页面。任何帮助将不胜感激。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 authentication forms-authentication
我正在开发一个 mvc .net 应用程序,并且我正在使用表单身份验证。我想在用户通过身份验证后将用户重定向到他请求的页面。任何帮助将不胜感激。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 authentication forms-authentication
如果您创建一个 ASP.NET MVC 3 或 4 Internet 应用程序项目,它将有一个完整的示例说明如何在身份验证时使用返回 url。
当您将 AuthorizeAttribute 添加到控制器以强制身份验证时,它会将用户重定向到您的 Login 方法,并自动附加 returnUrl 参数。从那里,您需要在显示登录表单时对其进行跟踪:
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
然后将其添加到您的登录表单的路由集合中:
@*//ReSharper disable RedundantAnonymousTypePropertyName*@
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@*//ReSharper restore RedundantAnonymousTypePropertyName*@
}
一旦用户提交登录,假设他们正确验证,您只需重定向到 returnUrl:
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
return RedirectToLocal(returnUrl);
}
最难的部分是通过 GET/POST 序列跟踪 ReturnUrl。
如果您想了解 AuthorizeAttribute 的工作原理,this StackOverflow 帖子显示了使用原始请求设置 returnUrl。
您还需要确保您验证 returnUrl 确实是一个本地 url,否则您将容易受到开放重定向攻击。 RedirectToLocal() 是 MVC 4 Internet 应用程序模板中的一个辅助方法,它执行此验证:
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
【讨论】:
Html.BeginForm 的 ReturnUrl = 部分,因为不需要明确的名称。在这种情况下,它是必需的。