我已经阅读了许多关于returnUrl的 SO 帖子,因为它与默认情况下的表单身份验证有关[authorize] MyController,但我没有阅读任何关于简单地传递 returnUrl 的内容,其中唯一的身份验证发生在 [HttpPost] 之后,使用登录或注册表单和匿名用户. 在这种情况下,我希望重定向来自原始链接并传递给通过表单身份验证对用户进行身份验证的操作。在用户 1) 单击注册或登录 ActionLinks 然后 2) 成功提交表单后,此重定向应将用户带回到正在查看的页面。这是在开发服务器上,因此 HTTPS 不是必需的 ATM。
这是没有传递 returnUrl 的必要语法/代码的元素
_登录部分:
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null}, htmlAttributes: new { id = "registerLink" })</li> //returnUrl???
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> // returnUrl???
登录视图:
@using (Html.BeginForm()){...} //new { returnUrl } ???
登录获取操作结果:
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
//There is other ways to store the route
TempData["ReturnUrl"] = returnUrl;
return View();
}
登录后操作结果:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(TempData["ReturnUrl"].ToString());
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
解决方案
感谢SlightlyMoist,我能够解决这个问题。虽然代码很小,但ViewContext.RouteData.Values["key"]IMO 的能力和专业知识似乎是无价的。因此,根据 SM 所做的唯一修改是在_LoginPartial视图的 ActionLinks 内完成的:
<li>
@Html.ActionLink("Register", "Register", "Account", routeValues: new {@returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), ViewContext.RouteData.Values["id"])}, htmlAttributes: new { id = "registerLink" })
</li>
<li>
@Html.ActionLink("Log in", "Login", "Account", routeValues: new {@returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), ViewContext.RouteData.Values["id"])}, htmlAttributes: new { id = "loginLink" })
</li>
也再次
按照 SM 的说法,这些ViewContext.HttpContext.Request.Url.PathAndQuery作品也很有效:
<li>
@Html.ActionLink("Register", "Register", "Account", routeValues: new {@returnUrl = ViewContext.HttpContext.Request.Url.PathAndQuery},htmlAttributes: new { id = "registerLink" })
</li>