我正在尝试从DelegatingHandler内读取使用IHttpContextAccessor接口及其默认实现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();
}
答案 0 :(得分:0)
您可以通过调用RouteData
扩展方法来拉出HttpContext
的{{3}},然后从那里读取各个值。这是一个示例:
var routeData = _httpContextAccessor.HttpContext.GetRouteData();
var siteName = routeData.Values["siteName"];
var accountID = routeData.Values["accountID"];
GetRouteData
扩展方法位于Microsoft.AspNetCore.Routing
命名空间中,因此您可能需要相应地添加using Microsoft.AspNetCore.Routing;
。