Welcome to todays blog!
The traditional way to use http context in web applications pre-ASP.NET Core days was to use HttpRequest.Context, however this approach only works within the context of the web page (e.g. using Context.User.Identity) or controller (HttpContext.Request).
To access the http context within the middle ware (custom classes and services) part of your application, you will need to make use of the IHttpContextAccessor interface of .NET Core (versions 2.0 onwards).
I will show you how to apply utilization of httpContext within your middleware.
In your Startup.cs file, apply the following source additions:
Add the following namespace:
using Microsoft.AspNetCore.Http;
In your ConfigureServices() method, add the line shown:
services.AddSingleton<IHttpContextAccessor,
HttpContextAccessor>();
This will inject the context accessor interface into the services container and make it available to your classes within the context of the application.
To use the above context accessor in your class, follow the steps below:
Step 1. Add the HTTP namespace
using Microsoft.AspNetCore.Http;
Step 2. Declare the http context to your accessor context within your constructor.
public class ReportService: IReportService
{
ApplicationDbContext _db;
..
UserManager<ApplicationUser> _userManager;
HttpContext _context;
public ReportService(ApplicationDbContext db,
UserManager<ApplicationUser> userManager,
IHttpContextAccessor httpContextAccessor,
..
)
{
_db = db;
..
_context = httpContextAccessor.HttpContext;
}
...
Step 3. Utilize the context within a method.
public async Task<List<BookLoan.Models.LoanReportViewModel>> MyOnLoanReport()
{
string curruser = _context.User.Identity.Name;
return await OnLoanReport(curruser);
}
That’s all!
I hope this was a useful post for you and makes your code more reusable when using http contexts.

Andrew Halil is a blogger, author and software developer with expertise of many areas in the information technology industry including full-stack web and native cloud based development, test driven development and Devops.