Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

HttpContext in ASP.NET Core

June 14, 2017
dotnet

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"];        }

        ...
    }
}

Comments

ovis January 19, 2018

very nice how would you go along getting and setting sessions values if your in domain layer?

Carl January 19, 2018

There’s a nice section on this at https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?tabs=aspnetcore2x “Working with Session State” that gives some info

In summary, after setting this up correctly in Startup, you can make calls like:

HttpContext.Session.SetString("PersonName", "Rick");
var name = HttpContext.Session.GetString("PersonName");

desayya October 26, 2018

how can i instantiate PersonData object? i want like this PersonData person = new PersonData ()?

thanks desayya

Carl October 26, 2018

Hi Desayya,

Thanks for the question. You can use dependency injection for this: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1


Interested in learning more about ASP.NET Core and React? My book is available now!
ASP.NET Core 3 and React