Recently I’ve been working on several small .NET Core web apps and was looking for two things. Firstly, a way to access Session in a data service directly, and not just by passing HttpContext reference down from controller. And secondly, log any unhandled exceptions that occur in the application. And the answer to both questions was IHttpContextAccessor interface!
Microsoft’s documentation about the interface mentioned above is very minimal, and just looking through different documentation/examples pages and websites you can get a better understanding of how you could use it. Therefore, I wanted to share two small examples in this blog post for a quick reference on how to use IHttpContextAccessor.
As the name suggests, IHttpContextAccessor allows to access HttpContext pretty much anywhere in the application by registering the interface with dependency injection (DI) framework, and injecting it into your constructor to access session or exception objects. See following examples:
- Accessing Session object from a data service.
- Accessing unhandled exception object.
- Register IHttpContextAccessor with Microsoft’s DI, and enabling Session in the application.
- Configure exception handler. Needed for #2 code snippet to work.
See code snippets below.
As you saw in the code snippets above getting IExceptionHandlerFeature feature in HttpContext would return an exception that has just occurred. This works like a global catch-all for any unhandled exception to be logged by an error logger. This works similarly like Application_Error method in Global.asax in previous versions of ASP.NET MVC.
Just to access session in a controller you could use HttpContext.Session, however using IHttpContextAccessor makes code look more unified, and some might find it easier to mock when unit testing.
Additionally, following HttpContext properties are accessible wherever you use IHttpContextAccessor.
IHttpContextAccessor is a new feature that come with .NET Core and brings unified DI approach to access HttpContext, Session, User etc., and even lets access additional Features like accessing unhandled exceptions if you wanted to log them.