我想獲得完整的 URL,而不僅僅是 the Path,不僅僅是 the Query,而不是RouteValues。
以原始形式出現的整個 URL。
如何在 ASP.NET Core Razor Pages 中做到這一點?
uj5u.com熱心網友回復:
您可以使用 的PageLink方法IUrlHelper來獲取頁面的絕對 URL。
在頁面處理程式中,IUrlHelper可以通過Url屬性訪問:
public async Task<IActionResult> OnPostAsync()
{
string url = Url.PageLink("/PageName", "PageHandler", routeValues);
...
}
如果要生成控制器操作的 URL,請使用ActionLink.
uj5u.com熱心網友回復:
您可以使用UriHelper擴展方法GetDisplayUrl()或GetEncodedUrl()從請求中獲取完整 URL。
獲取顯示網址()
以僅適合顯示的完全非轉義形式(QueryString 除外)回傳請求 URL 的組合組件。此格式不應用于 HTTP 標頭或其他 HTTP 操作。
獲取編碼網址()
以完全轉義的形式回傳請求 URL 的組合組件,適用于 HTTP 標頭和其他 HTTP 操作。
用法:
using Microsoft.AspNet.Http.Extensions;
...
string url = HttpContext.Request.GetDisplayUrl();
// or
string url = HttpContext.Request.GetEncodedUrl();
uj5u.com熱心網友回復:
您可以創建一個擴展類來使用 IHttpContextAccessor 介面來獲取 HttpContext。獲得背景關系后,您可以從 HttpContext.Request 獲取 HttpRequest 實體并使用其屬性 Scheme、Host、Protocol 等,如下所示:
string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
例如,您可以要求使用 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);
}
....
}
您可以在 Startup 類(Startup.cs 檔案)上執行以下操作:
public void Configure(IApplicationBuilder app)
{
...
var httpContextAccessor =
app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
UrlHelperExtensions.Configure(httpContextAccessor);
...
}
您可能會想出不同的方法在您的擴展類中獲取 IHttpContextAccessor,但是如果您希望最終將您的方法保留為擴展方法,您將需要將 IHttpContextAccessor 注入到您的靜態類中。(否則您將需要 IHttpContext 作為每次呼叫的引數)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393730.html
上一篇:將引數傳遞給MVC控制器
