Asp.Net 5 (vNext) 中的 HttpRequest
类包含(除其他外)有关请求 URL 的解析详细信息,例如 Scheme
、Host
、Path
等。
不过,我还没有发现任何公开原始请求 URL 的地方——只有这些解析的值。 (在以前的版本中有 Request.Uri
)
我可以取回原始 URL,而不必从 HttpRequest 上可用的组件中拼凑起来吗?
看起来您无法直接访问它,但您可以使用框架构建它:
Microsoft.AspNetCore.Http.Extensions.UriHelper.GetFullUrl(Request)
您也可以将上述方法用作扩展方法。
这将返回 string
而不是 Uri
,但它应该可以达到目的! (这似乎也起到了 UriBuilder
的作用。)
感谢@mswietlicki 指出它只是被重构而不是丢失!还要@CF 指出我的答案中的命名空间变化!
添加 Nuget 包 / 使用:
using Microsoft.AspNetCore.Http.Extensions;
(在 ASP.NET Core RC1 中,这是在 Microsoft.AspNet.Http.Extensions 中)
然后您可以通过执行以下命令获取完整的 http 请求 url:
var url = httpContext.Request.GetEncodedUrl();
或者
var url = httpContext.Request.GetDisplayUrl();
取决于目的。
using
指令,如答案中所述,因为这些不是“正常”方法,而是扩展方法。
如果您真的想要实际的原始 URL,可以使用以下扩展方法:
public static class HttpRequestExtensions
{
public static Uri GetRawUrl(this HttpRequest request)
{
var httpContext = request.HttpContext;
var requestFeature = httpContext.Features.Get<IHttpRequestFeature>();
return new Uri(requestFeature.RawTarget);
}
}
此方法利用请求的 RawTarget
,它不会出现在 HttpRequest
对象本身上。此属性是在 ASP.NET Core 1.0.0 版本中添加的。确保您正在运行该版本或更新版本。
笔记!如文档所述,此属性公开了原始 URL,因此尚未对其进行解码:
此属性在内部不用于路由或授权决策。它尚未经过 UrlDecoded,使用时应小心。
RawTarget
未在 IHttpRequestFeature
上定义)。你能想出一个替代方案吗?
RawTarget
在 1.0 版本中添加,back in may。你确定你运行的是最新版本吗?
在 .NET Core 剃须刀中:
@using Microsoft.AspNetCore.Http.Extensions
@Context.Request.GetEncodedUrl() //Use for any purpose (encoded for safe automation)
您也可以使用而不是第二行:
@Context.Request.GetDisplayUrl() //Use to display the URL only
其他解决方案不太适合我的需求,因为我直接想要一个 URI
对象,我认为在这种情况下最好避免字符串连接(也)所以我创建了这个扩展方法而不是使用 UriBuilder
并且也适用于http://localhost:2050
等网址:
public static Uri GetUri(this HttpRequest request)
{
var uriBuilder = new UriBuilder
{
Scheme = request.Scheme,
Host = request.Host.Host,
Port = request.Host.Port.GetValueOrDefault(80),
Path = request.Path.ToString(),
Query = request.QueryString.ToString()
};
return uriBuilder.Uri;
}
(80)
应该是 (-1)
。当您在“主机”标头中省略端口的 https 方案时,这将生成错误的 Uri(例如 https://myweb:80/
,如果使用 (-1)
,它将是 https://myweb
)。
以下扩展方法从 pre-beta5 UriHelper
中重现了逻辑:
public static string RawUrl(this HttpRequest request) {
if (string.IsNullOrEmpty(request.Scheme)) {
throw new InvalidOperationException("Missing Scheme");
}
if (!request.Host.HasValue) {
throw new InvalidOperationException("Missing Host");
}
string path = (request.PathBase.HasValue || request.Path.HasValue) ? (request.PathBase + request.Path).ToString() : "/";
return request.Scheme + "://" + request.Host + path + request.QueryString;
}
这个扩展对我有用:
using Microsoft.AspNetCore.Http;
public static class HttpRequestExtensions
{
public static string GetRawUrl(this HttpRequest request)
{
var httpContext = request.HttpContext;
return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.Path}{httpContext.Request.QueryString}";
}
}
在 ASP.NET 5 beta5 中:
Microsoft.AspNet.Http.Extensions.UriHelper.Encode(
request.Scheme, request.Host, request.PathBase, request.Path, request.QueryString);
不定期副业成功案例分享
GetEncodedUri
或GetDisplayUri
,具体取决于您的用例。