如何在ASP.NET Core中使用HttpContextAccessor读取URI参数

时间:2019-06-05 13:41:00

标签: c# asp.net-core httpcontext route-parameters

我正在尝试从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();
}

1 个答案:

答案 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;