4

我已经阅读了许多关于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>
4

2 回答 2

6

只需将当前路由 / URL 解析为登录操作链接中的 routeValue。

像这样的东西应该可以解决问题

@Html.ActionLink("Login", "Login", "Account", 
    new {@returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString())})
于 2014-04-02T05:25:52.303 回答
5

类似的想法,只是我只是在视图中添加了 ViewBag.ReturnUrl,并修改了 Register 和 Login 方法。这是因为并非所有登录和注册位置都希望返回页面,这样您就可以逐个查看地进行控制。

@{
    ViewBag.Title = "My Page";
    ViewBag.ReturnUrl = "/Home/Live";
}

在 _LoginPartial 中:

@Html.ActionLink( "Log in", "Login", new { area = "", controller = "Account", ReturnUrl=ViewBag.ReturnUrl }, new { id = "loginLink" } )
于 2015-09-08T09:17:17.640 回答