2

我正在尝试使用 IHttpContextAccessor 接口及其默认实现 HttpContextAccessor 从 DelegatingHandler 中读取发送到 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();
}
4

1 回答 1

2

您可以通过调用扩展方法来提取HttpContext's ,然后从那里读取各个值。这是一个例子:RouteDataGetRouteData

var routeData = _httpContextAccessor.HttpContext.GetRouteData();
var siteName = routeData.Values["siteName"];
var accountID = routeData.Values["accountID"];

GetRouteData扩展方法位于命名Microsoft.AspNetCore.Routing空间中,因此您可能需要using Microsoft.AspNetCore.Routing;相应地添加一个。

于 2019-06-05T14:06:20.853 回答