How to Get Custom Header Value in .NET Core

How to get custom header value in NET Core

Today in this article, we shall see How to get custom header value in .NET Core WebAPI.

You may get a requirement to read the custom header value programmatically in your .NET Core WebAPI.

These headers are useful means of storing metadata like credentials, secured tokens, custom headers, version details if following API versioning through content negotiation.

There are many ways to retrieve header values. In this article, we will see a very simple approach to retrieve the same.

Get Custom Header .NET Core – Access Custom header in Middleware

HttpContext will be accessible through the WebAPI pipeline and can be available through middleware (as shown in the above example) or .NET Filters (Action Filters or Exception Filters etc) or HTTPRequest objects if dealing with console or desktop applications.

Overall .NET Core middleware pipeline provides the ability to read or update these headers easily.

How to get custom header value in NET Core

As shown above, the header value can be easily read through the HttpContext object.

Please add below generic logic to read through any of the custom headers.

///

private static void ReadCustomHeader(out string customHeader, HttpContext context)
        {
            customHeader = string.Empty;
            if (context.Request.Headers.TryGetValue("thecodebuzz", out var traceValue))
            {
                customHeader = traceValue;
            }
        }

Get Custom Header .NET Core – Access Custom header in Controller

Accessing custom headers through the controller is even easier. One can use a Request object to access the required custom headers.

        ///

        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            Request.Headers.TryGetValue("thecodebuzz", out var traceValue);
            return Ok();
        }

How to get custom header value in NET Core

Above logic can be used to retrive headers for both Request or Response object.

Please note that code “context.Request.Headers” is a dictionary object and contains a collection of headers with Key and value pairs.

The same logic can also be used for “context.Response.Headers”.

Get Custom Header .NET Core – Using IHTTPContextAccessor to extract custom header

The abovediscussed HttpContext or Request class gives us access to metadata including headers of given HttpContext within Controller.

However, if you need to access headers or any HttpContext metadata in other services or modules then please use IHTTPContextAccessor.

class EmployeeRepository : IEmployeeRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EmployeeRepository( IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
       
        public void GetEmployeeByID(int employeeID)
        {
         string header = 
        _httpContextAccessor.HttpContext.Request.Headers["X-Custom-Header"];
         PerformBusinessLogic(header);
        }

..
}

Get Custom Header .NET Core – Extract All Header and Print it

You might find the need to extract all request headers and read or print them for troubleshooting purposes etc.

Here is a simple API that can be used to print headers from middleware or controller etc.

        [HttpGet("employee")]
        public IActionResult GetDetails()
        {
            PrintHeader(Request.Headers);
            return Ok(header);

        }
  private void PrintHeader(IHeaderDictionary dict)
        {
            foreach (StringValues keys in dict.Keys)
            {
                string str = "Key : " + keys + ":  Values : " + dict[keys];
                Console.WriteLine(str);
            }

        }

References:

For more details please refer: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iheaderdictionary?view=aspnetcore-3.0

Get access token from HttpContext:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!




Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

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