Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core 如何在ASP.NET Core中获取登录重定向的当前应用程序相对url_Asp.net Core_Asp.net Core Mvc - Fatal编程技术网

Asp.net core 如何在ASP.NET Core中获取登录重定向的当前应用程序相对url

Asp.net core 如何在ASP.NET Core中获取登录重定向的当前应用程序相对url,asp.net-core,asp.net-core-mvc,Asp.net Core,Asp.net Core Mvc,我试图实现简单的逻辑,这样用户在站点中的任何页面都可以在登录后重定向回。要做到这一点,我似乎需要一种简单的方法来获取当前请求的相对url 我尝试在my _LoginPartial.cshtml中使用完整url和如下链接: <a asp-controller="Login" asp-action="Index" asp-route-returnUrl="@Context.Request.GetEncodedUrl()">Log in</a> 似乎应该有一个简单的内置方法来

我试图实现简单的逻辑,这样用户在站点中的任何页面都可以在登录后重定向回。要做到这一点,我似乎需要一种简单的方法来获取当前请求的相对url

我尝试在my _LoginPartial.cshtml中使用完整url和如下链接:

<a asp-controller="Login" asp-action="Index" asp-route-returnUrl="@Context.Request.GetEncodedUrl()">Log in</a>

似乎应该有一个简单的内置方法来获取当前的相对url。我是否遗漏了什么,或者我是否需要为此实现自己的扩展方法?我使用的是RC1,你是说Context.Request.Path吗

我很快制作了一个带有HomeController、Index.cshtml和Second.cshtml的示例项目。第二个.cshtml如下所示:

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
<h1>@ViewBag.Title</h1>
<a asp-controller="Home" asp-action="Index" asp-route-returnUrl="@Context.Request.Path">Log in</a>
@addTagHelper“*,Microsoft.AspNet.Mvc.TagHelpers”
@视图包。标题
您有Request.Query和/或Request.QueryString来连接完整的URL


如果愿意,您可以在HttpRequest类上创建一个扩展方法,例如将路径和查询字符串一起返回。

有一个扩展方法:
Request.GetDisplayUrl()
返回
https://localhost/MyController/MyAction?Param1=blah

或编码版本
Request.GetEncodedUrl()


您必须向其中任何一个添加:
使用Microsoft.AspNetCore.Http.Extensions

要在ASP.NET Core 2.0或更高版本中获取相对路径和查询字符串,可以使用名为
GetEncodedPathAndQuery()的HttpRequest扩展方法

要在Razor视图中使用此方法,请使用Microsoft.AspNetCore.Http.Extensions在Razor视图或
\u ViewImports.cshtml
中添加
@

您的
标签将是:

<a asp-controller="Home" asp-action="Index" 
   asp-route-returnUrl="@Context.Request.GetEncodedPathAndQuery()">Log in</a>
登录

这在一般情况下是可行的,但在许多情况下我可能也需要查询字符串,如果有类似.Request.PathAndQuery的内容,那就太好了,但如果没有在OK中构建任何内容,我可以实现我自己的解决方案,尽管这不是我所希望的答案,也没有告诉我任何我不知道的事情,但这是我所怀疑的。我希望asp.net团队将此问题视为反馈,因为我认为许多人会为这一非常常见的需求实现类似的扩展方法,因此似乎应该构建它in@JoeAudette完整url的一个简单方法是使用razor来获取这两个:@{string url=Context.Request.Path;string qs=Context.Request.QueryString.Value;}然后,您可以在returnUrl中同时使用这两个选项:asp路由returnUrl=”@url@qs"
<a href="/?returnUrl=%2FHome%2FSecond">Log in</a>
<a asp-controller="Home" asp-action="Index" 
   asp-route-returnUrl="@Context.Request.GetEncodedPathAndQuery()">Log in</a>