Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing HTTP Headers in ASP.Net Core Business Logic

I am using ASP.Net core and I have a requirement to access a specific HTTP Header in a business logic class (not a controller or action).

To provide a full picture of the configuration here, I have a custom ASP.Net Core Middleware which based on some logic will add a value into a custom HTTP Header, it is the value from this header that I need to access in the business logic class.

Currently the way that I achieve this is to inject an HttpContextAccessor, using the following DI registration.

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In the class which requires access to the HTTP Headers I then request an IHttpContextAccessor using constructor injection and use this to access the relevant HTTP Header.

Doing the above works fine and gives me the results that I require, looking around various articles on the Internet however the general consensus appears to be to avoid using HttpContext.Current in ASP.Net Core.

If the above is the case, is there a better way for my business logic class to access the value that my custom middleware is inserting into a custom HTTP Header?

I should be clear, whilst at present the middleware is storing the required value in a HTTP Header for use by the business logic class, I am open to other methods of the middleware making the required value available to the business logic class if there is a better approach.

Any questions or clarifications, please let me know.

like image 482
Chris Lawrence Avatar asked Mar 16 '17 18:03

Chris Lawrence


People also ask

How do I add a header to my HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers. For example: oRequest = RequestBuilder:Build('GET', oURI) :AddHeader('MyCustomHeaderName','MyCustomHeaderValue') :AddHeader('MySecondHeader','MySecondHeaderValue') :Request.


1 Answers

There is no HttpContext.Current in ASP.Net Core, so it's easy to avoid using it. You would have to implement your own extension method if you wanted it, but the general feeling in the .Net Core community is that it's much better to use IHttpContextAccessor.

In earlier versions of .Net Core an implementation of IHttpContextAccessor was auto registered in the DI container. In more current version you have to register it yourself with the line of code you mentioned:

 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Injecting IHttpContext into your method that needs access to the headers is a workable approach. Or if you like you could use a helper method that places a copy of the headers in a simpler structure and then pass that object in to your class since it doesn't really need access to the full HttpContext.

like image 192
RonC Avatar answered Sep 30 '22 22:09

RonC