如何在 ASP.NET Core 中使用 HttpContextAccessor 读取 URI 参数
How to read URI Parameters using HttpContextAccessor in ASP.NET Core
我正在尝试使用 IHttpContextAccessor 接口及其从 DelegatingHandler 中的默认实现 HttpContextAccessor 读取发送到 WEB API 操作方法的 URL 参数。
控制器看起来像这样:
[HttpPost("{siteName}/{accountID}")]
public async Task<ActionResult<AirRequest>> Post(AirCModel model, string siteName, string accountID)
{
}
我想读取 DelegatingHandler
中的值 {siteName}/{accountID}
public class AuthenticationDelegatingHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthenticationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var siteNAme = _httpContextAccessor ???
}
}
在 Startup.cs 我注入了 HttpContext 服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddHttpContextAccessor();
}
您可以提取 HttpContext
的 RouteData
with a call to the GetRouteData
扩展方法,然后从那里读取各个值。这是一个例子:
var routeData = _httpContextAccessor.HttpContext.GetRouteData();
var siteName = routeData.Values["siteName"];
var accountID = routeData.Values["accountID"];
GetRouteData
扩展方法位于 Microsoft.AspNetCore.Routing
命名空间中,因此您可能需要相应地添加 using Microsoft.AspNetCore.Routing;
。
我正在尝试使用 IHttpContextAccessor 接口及其从 DelegatingHandler 中的默认实现 HttpContextAccessor 读取发送到 WEB API 操作方法的 URL 参数。
控制器看起来像这样:
[HttpPost("{siteName}/{accountID}")]
public async Task<ActionResult<AirRequest>> Post(AirCModel model, string siteName, string accountID)
{
}
我想读取 DelegatingHandler
中的值 {siteName}/{accountID}public class AuthenticationDelegatingHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthenticationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var siteNAme = _httpContextAccessor ???
}
}
在 Startup.cs 我注入了 HttpContext 服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddHttpContextAccessor();
}
您可以提取 HttpContext
的 RouteData
with a call to the GetRouteData
扩展方法,然后从那里读取各个值。这是一个例子:
var routeData = _httpContextAccessor.HttpContext.GetRouteData();
var siteName = routeData.Values["siteName"];
var accountID = routeData.Values["accountID"];
GetRouteData
扩展方法位于 Microsoft.AspNetCore.Routing
命名空间中,因此您可能需要相应地添加 using Microsoft.AspNetCore.Routing;
。