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

Joe*_*tte 5 asp.net-core-mvc asp.net-core

我正在尝试实现简单的逻辑,以便用户在网站上访问的任何页面都可以在用户登录后重定向回该页面。为此,似乎我需要一种简单的方法来获取当前请求的相对URL。

我尝试在_LoginPartial.cshtml中将完整的URL与这样的链接一起使用:

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

但这会导致错误:

A URL with an absolute path is considered local if it does not have a host/authority part. URLs using virtual paths ('~/') are also local.
Run Code Online (Sandbox Code Playgroud)

似乎应该有一个简单的内置方法来获取当前的相对URL。我是否缺少某些东西,或者需要为此实现自己的扩展方法?我正在使用RC1

Dan*_*aan 6

您的意思是Context.Request.Path吗?

我很快用HomeController,Index.cshtml和Second.cshtml制作了一个示例项目。Second.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>
Run Code Online (Sandbox Code Playgroud)

锚标记以如下方式呈现给浏览器(已通过Chrome开发者工具测试):

<a href="/?returnUrl=%2FHome%2FSecond">Log in</a>
Run Code Online (Sandbox Code Playgroud)

您具有Request.Query和/或Request.QueryString来连接完整URL。

您可以在HttpRequest类上创建扩展方法,例如,如果需要,可以一起返回Path和QueryString。