var request = HttpContext.Request;
var _baseURL = $"{request.Scheme}://{request.Host}";
var fullUrl = _baseURL+HttpContext.Request.Path + HttpContext.Request.QueryString;
You could create an extension class to use the IHttpContextAccessor interface to get the HttpContext . Once you have the context, then you can get the HttpRequest instance from HttpContext.Request and use its properties Scheme , Host , Protocol etc. as in:
For example, you could require your class to be configured with an HttpContextAccessor :
public static class UrlHelperExtensions
{
private static IHttpContextAccessor HttpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
}
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
....
}
Which is something you can do in your Startup class (Startup.cs file):
public void Configure(IApplicationBuilder app)
{
...
var httpContextAccessor =
app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
UrlHelperExtensions.Configure(httpContextAccessor);
...
}
You could probably come up with different ways of getting the IHttpContextAccessor in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject the IHttpContextAccessor into your static class. (Otherwise, you will need the IHttpContext as an argument on each call).
5条答案
按热度按时间qvtsj1bj1#
您可以使用
UriHelper
扩展方法GetDisplayUrl()
或GetEncodedUrl()
从请求中获取完整的URL。获取显示URL()
以仅适用于显示的完全未转义格式(QueryString除外)返回请求URL的组合组件。此格式不应用于HTTP标头或其他HTTP操作。
获取编码URL()
以适合在HTTP标头和其他HTTP操作中使用的完全转义形式返回请求URL的组合组件。
用法:
lf5gs5x22#
您可以使用
IUrlHelper
的PageLink
方法来取得网页的绝对URL。在页面处理程序(或控制器)中,可以通过
Url
属性访问IUrlHelper
:如果要生成控制器操作的URL,请使用
ActionLink
。mmvthczy3#
您可以尝试使用
HttpContext.Request.Scheme + HttpContext.Request.Host
来获取https://localhost:xxxx
,然后使用HttpContext.Request.Path + HttpContext.Request.QueryString
来获取路径和查询:wgxvkvu94#
You could create an extension class to use the
IHttpContextAccessor
interface to get theHttpContext
. Once you have the context, then you can get theHttpRequest
instance fromHttpContext.Request
and use its propertiesScheme
,Host
,Protocol
etc. as in:For example, you could require your class to be configured with an
HttpContextAccessor
:Which is something you can do in your
Startup
class (Startup.cs file):You could probably come up with different ways of getting the
IHttpContextAccessor
in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject theIHttpContextAccessor
into your static class. (Otherwise, you will need theIHttpContext
as an argument on each call).3df52oht5#
你可以这样做。在
.net core