Search code examples
c#asp.net-corehttpcontextroute-parameters

How to read URI Parameters using HttpContextAccessor in ASP.NET Core


I am trying to read the URL parameters sent to an WEB API Action Method using the IHttpContextAccessor interface and its default implementation HttpContextAccessor from within a DelegatingHandler.

The controller looks like this:

[HttpPost("{siteName}/{accountID}")]
public async Task<ActionResult<AirRequest>> Post(AirCModel model, string siteName, string accountID)
{

}

I want to read the value {siteName}/{accountID} within a DelegatingHandler

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 ???
    }
}

in the Startup.cs I injected the HttpContext Service:

public void ConfigureServices(IServiceCollection services)
{                   
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddHttpContextAccessor();
}

Solution

  • You can pull out the HttpContext's RouteData with a call to the GetRouteData extension method and then read the individual values from there. Here's an example:

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

    The GetRouteData extension method lives in the Microsoft.AspNetCore.Routing namespace, so you might need to add a using Microsoft.AspNetCore.Routing; accordingly.