Jon*_*ton 63 uri request asp.net-core
的HttpRequest在Asp.Net 5(vNext)类包含(除其他事项外)解析有关的URL请求,诸如细节Scheme,Host,Path等.
我还没有发现任何公开原始请求URL的地方 - 只有这些解析的值.(以前的版本有Request.Uri)
我可以获取原始URL而无需将其与HttpRequest上可用的组件拼凑在一起吗?
Mat*_*rey 62
看起来您无法直接访问它,但您可以使用框架构建它:
Microsoft.AspNetCore.Http.Extensions.UriHelper.GetFullUrl(Request)
Run Code Online (Sandbox Code Playgroud)
您也可以使用上面的扩展方法.
这返回一个string而不是一个Uri,但它应该服务于目的!(这似乎也起到了作用UriBuilder.)
感谢@mswietlicki指出它刚被重构而不是丢失!并且@CF指出我的答案中的命名空间更改!
小智 46
添加Nuget包/使用:
using Microsoft.AspNetCore.Http.Extensions;
Run Code Online (Sandbox Code Playgroud)
(在ASP.NET Core RC1中,这是在Microsoft.AspNet.Http.Extensions中)
然后你可以通过执行以下命令获取完整的http请求URL:
var url = httpContext.Request.GetEncodedUrl();
Run Code Online (Sandbox Code Playgroud)
要么
var url = httpContext.Request.GetDisplayUrl();
Run Code Online (Sandbox Code Playgroud)
取决于目的.
如果您真的想要实际的原始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);
}
}
Run Code Online (Sandbox Code Playgroud)
此方法利用RawTarget请求,该请求未在HttpRequest对象本身上浮出.此属性已添加到ASP.NET Core的1.0.0版本中.确保您正在运行该版本或更新版本.
注意!此属性公开原始 URL,因此尚未解码,如文档所示:
此属性不在内部用于路由或授权决策.它不是UrlDecoded,应该小心使用它.
在ASP.NET Core 2.x剃须刀页面中:
@using Microsoft.AspNetCore.Http.Extensions
@Context.Request.GetEncodedUrl() //Use for any purpose (encoded for safe automation)
Run Code Online (Sandbox Code Playgroud)
还有另一个功能:
@Context.Request.GetDisplayUrl() //Use to display the URL only
Run Code Online (Sandbox Code Playgroud)
以下扩展方法重现了 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;
}
Run Code Online (Sandbox Code Playgroud)
这个扩展对我有用:
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}";
}
}
Run Code Online (Sandbox Code Playgroud)
其他解决方案不能很好地满足我的需求,因为我直接想要一个URI对象,并且我认为在这种情况下最好避免字符串连接(因此),所以我创建了这种扩展方法,而不是使用a,UriBuilder并且还可以与url一起使用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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35113 次 |
| 最近记录: |