asp.net-mvc ASP.NET MVC 中的 ReturnUrl

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:31:03  来源:igfitidea点击:

ReturnUrl in ASP.NET MVC

asp.net-mvc

提问by Kevin Pang

I currently have a login link on my application that looks something like this:

我目前在我的应用程序上有一个登录链接,如下所示:

<a href="/login?ReturnUrl=" + <%= Request.RawUrl %>>Login</a>

I want to handle the POST command on the login page in the controller action below:

我想在下面的控制器操作中处理登录页面上的 POST 命令:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(string returnUrl)
{
    // Authenticate user

    return Redirect(returnUrl);
}

The problem here is if the RawUrl is something with multiple url parameters like "somepage?param1=1&param2=2&param3=3", then the returnUrl that gets passed into the Login action is truncated after the first ampersand: "somepage?param1=1".

这里的问题是,如果 RawUrl 是具有多个 url 参数的内容,例如“somepage?param1=1¶m2=2¶m3=3”,则传递到 Login 操作的 returnUrl 在第一个&符号之后被截断:“somepage?param1=1” .

I've tried UrlEncoding the RawUrl but that seem to make any difference. It seems that the ASP.NET MVC framework here is UrlDecoding the url params before mapping them to the controller action parameters, which ends up stripping off the additional url parameters I want to see in my returnUrl parameter.

我试过 UrlEncoding RawUrl 但这似乎有什么不同。似乎这里的 ASP.NET MVC 框架是在将 url 参数映射到控制器操作参数之前对它们进行 UrlDecoding,这最终剥离了我想在 returnUrl 参数中看到的其他 url 参数。

Is there any way around this? I know I could just use Request.Path and parse out the values I need, but I thought I'd see if there was a cleaner approach first.

有没有办法解决?我知道我可以只使用 Request.Path 并解析出我需要的值,但我想我会先看看是否有更简洁的方法。

回答by Craig Stuntz

You're probably encoding the links incorrectly. Yes, they do need to be encoded. Here is how we do it:

您可能对链接的编码不正确。是的,它们确实需要编码。这是我们如何做到的:

<a href="<%= Url.Action("Delete", "TimeRecord", 
    new RouteValueDictionary(new { id = timeRecord.AltId, 
    returnUrl=ViewContext.HttpContext.Request.Url.PathAndQuery }) ) %>">

回答by Nick Berardi

Make sure you URL encode the RawUrl before using it.

在使用 RawUrl 之前,请确保对它进行 URL 编码。

<%= Url.Encode(Request.RawUrl) %>

This should do it for you.

这应该为你做。