如何在ASP.NET核心网页中获得完整的URL?

0s7z1bwu  于 2022-12-05  发布在  .NET
关注(0)|答案(5)|浏览(237)

我想获得完整的URL,而不仅仅是PathQueryRouteValues
以原始形式出现的整个URL。
我如何在ASP.NET核心剃刀页中做到这一点?

qvtsj1bj

qvtsj1bj1#

您可以使用UriHelper扩展方法GetDisplayUrl()GetEncodedUrl()从请求中获取完整的URL。

获取显示URL()

以仅适用于显示的完全未转义格式(QueryString除外)返回请求URL的组合组件。此格式不应用于HTTP标头或其他HTTP操作。

获取编码URL()

以适合在HTTP标头和其他HTTP操作中使用的完全转义形式返回请求URL的组合组件。
用法:

using Microsoft.AspNetCore.Http.Extensions;
...
string url = HttpContext.Request.GetDisplayUrl();
// or
string url = HttpContext.Request.GetEncodedUrl();
lf5gs5x2

lf5gs5x22#

您可以使用IUrlHelperPageLink方法来取得网页的绝对URL。
在页面处理程序(或控制器)中,可以通过Url属性访问IUrlHelper

public async Task<IActionResult> OnPostAsync()
{
    string url = Url.PageLink("/PageName", "PageHandler", routeValues);
    ...
}

如果要生成控制器操作的URL,请使用ActionLink

  • 适用于ASP.NET Core 3.0及更高版本。*
mmvthczy

mmvthczy3#

您可以尝试使用HttpContext.Request.Scheme + HttpContext.Request.Host来获取https://localhost:xxxx,然后使用HttpContext.Request.Path + HttpContext.Request.QueryString来获取路径和查询:

var request = HttpContext.Request;
var _baseURL = $"{request.Scheme}://{request.Host}";
var fullUrl = _baseURL+HttpContext.Request.Path + HttpContext.Request.QueryString;
wgxvkvu9

wgxvkvu94#

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:

string scheme = HttpContextAccessor.HttpContext.Request.Scheme;

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).

3df52oht

3df52oht5#

你可以这样做。在.net core

@using Microsoft.AspNetCore.Http
@{
    string url = Context.Request.Path;
}

相关问题