在以前的asp.net版本中,我们可以使用
@Request.Url.AbsoluteUri
但它似乎已经改变了。我们怎样才能在asp.net core 1.0中做到这一点?
您必须单独获取主机和路径。
@[email protected]
您需要scheme,host,path和queryString
@string.Format("{0}://{1}{2}{3}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path, Context.Request.QueryString)
或使用新的C#6功能“字符串插值”
@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")
你可以使用Request
的扩展方法:
Request.GetDisplayUrl()
使用Uri的AbsoluteUri属性,你必须使用.Net核心从这样的请求构建Uri,
var location = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}");
var url = location.AbsoluteUri;
例如如果请求网址是'http://www.contoso.com/catalog/shownew.htm?date=today',则返回相同的网址。
public string BuildAbsolute(PathString path, QueryString query = default(QueryString), FragmentString fragment = default(FragmentString))
{
var rq = httpContext.Request;
return Microsoft.AspNetCore.Http.Extensions.UriHelper.BuildAbsolute(rq.Scheme, rq.Host, rq.PathBase, path, query, fragment);
}
这显然总是可以在.net core 1.0中使用Microsoft.AspNetCore.Http.Extensions
,它增加了HttpRequest
的扩展以获得完整的URL; GetEncodedUrl。
例如从剃刀视图:
@using Microsoft.AspNetCore.Http.Extensions
...
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>
从2.0开始,也有相对路径和查询GetEncodedPathAndQuery。
如果您还希望从请求中获取端口号,则需要通过AspNet Core的Request.Host
属性访问它。
Request.Host
属性不仅仅是一个字符串,而是一个同时包含主机域和端口号的对象。如果端口号是专门写在URL中的(即"https://example.com:8080/path/to/resource"
),那么调用Request.Host
将为您提供主机域和端口号,如下所示:"example.com:8080"
。
如果您只想要主机域的值或只想要端口号的值,那么您可以单独访问这些属性(即Request.Host.Host
或Request.Host.Port
)。
您可以考虑使用此扩展方法(来自Microsoft.AspNetCore.Http.Extensions
命名空间:
@Context.Request.GetDisplayUrl()
对于我的一些项目,我更喜欢灵活的解决方案有两种扩展方法。
1)第一种方法从传入的请求数据创建Uri
对象(通过可选参数的一些变体)。 2)第二个方法接收Uri
对象并以下列格式返回string
(没有斜杠):Scheme_Host_Port
public static Uri GetUri(this HttpRequest request, bool addPath = true, bool addQuery = true)
{
var uriBuilder = new UriBuilder
{
Scheme = request.Scheme,
Host = request.Host.Host,
Port = request.Host.Port.GetValueOrDefault(80),
Path = addPath ? request.Path.ToString() : default(string),
Query = addQuery ? request.QueryString.ToString() : default(string)
};
return uriBuilder.Uri;
}
public static string HostWithNoSlash(this Uri uri)
{
return uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
}
用法:
//before >> https://localhost:44304/information/about?param1=a¶m2=b
Request.GetUri(addQuery: false);
//after >> https://localhost:44304/information/about
//before >> https://localhost:44304/information/about?param1=a¶m2=b
new Uri("https://localhost:44304/information/about?param1=a¶m2=b").GetHostWithNoSlash();
//after >> https://localhost:44304
接受的答案帮助了我,就像来自@padigan的评论一样,但如果你想包含查询字符串参数,就像我的情况一样,那么试试这个:
@[email protected]()
您需要在视图中添加@using Microsoft.AspNetCore.Http.Extensions
才能使GetEncoded PathAndQuery()方法可用。