在ASP.NET Core 1.0中如何在视图中获取当前URL

157

在之前的asp.net版本中,我们可以使用

@Request.Url.AbsoluteUri

但它似乎已经改变了。我们如何在asp.net core 1.0中做到这一点?


2
像这样吗?https://dev59.com/J14c5IYBdhLWcg3wQoc5 - DavidG
6
看起来你现在可以使用UriHelper.GetDisplayUrl(Request)。 - Mark G
13个回答

4
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";

1

如果您想在 Razor 侧使用 URL,还有一种替代方法可以获取主页应用程序的 URL:

Url.Content("~/.....")

示例

在下面的示例中,我想生成一个 QR 码并将其显示在 img 标签的 src 中。由于在 Action 中使用了自定义路由注释,因此无法使用 @URL.Action,因此我使用 ~ 作为替代方案,如下所示:

<script>
    $("#imgCode").attr("src", "@(Url.Content("~/generateQr/"))"+ code);

</script>

控制器端

[Route("/generateQr/{code}")]
...

0

ILSpy 展示了在 Microsoft.Owin.dll 中是如何完成的。

// Microsoft.Owin.OwinRequest
using System;

/// <summary>
/// Gets the uniform resource identifier (URI) associated with the request.
/// </summary>
/// <returns>The uniform resource identifier (URI) associated with the request.</returns>
public virtual Uri Uri => new Uri(string.Concat(Scheme, Uri.SchemeDelimiter, Host, PathBase, Path, QueryString));

我不知道他们为什么删除了这个属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接