Know Further About HttpContext in ASP.NET Core

HttpContext is largely the same in asp.net core as it’s always been. However, one difference is that it is not automatically as available everywhere in your code base as it used to be …

If you are in a controller then you are okay – HttpContext is a property of ControllerBase:

[HttpGet("{id}")]
public string Get(int id)
{
    var tenantId = (string)HttpContext.Items["tenant"];    ...
}

If you are in middleware then you are okay – HttpContext is passed in as a parameter:

public async Task Invoke(HttpContext httpContext)
{
    var apiKey = httpContext.Request.Headers["X-API-Key"].FirstOrDefault();
    // TODO get the tenant from the data store from an API key
    var tenantId = "";
    httpContext.Items["tenant"] = tenantId;

    await next.Invoke(httpContext);
}

However, if you are in the domain layer, the you need to do some work …

First you need to register IHttpContextAccessor for dependency injection in the apps

public class Startup
{
	...

	public void ConfigureServices(IServiceCollection services)
	{
	    // Add framework services.
	    services.AddMvc();
	    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();	    ...
	}

	...
}

In your domain layer, you then need to bring in Microsoft.AspNetCore.Http via nuget and use dependency injection to get a reference to IHttpContextAccessor which in tern gives you a reference to HttpContext …

using Microsoft.AspNetCore.Http;
using System;

namespace Domain
{
    public class PersonData
    {
        private string tenantId;

        public PersonData(IHttpContextAccessor httpContextAccessor)
        {
            tenantId = (string)httpContextAccessor.HttpContext.Items["tenant"];        }

        ...
    }
}

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *