Joydip Kanjilal
Contributor

How to read request headers in ASP.NET Core 5 MVC

how-to
May 11, 20215 mins
C#Microsoft .NETSoftware Development

Learn how to read request headers and work with optional data that is passed between the server and client in ASP.NET Core 5 applications.

A magnifying lens sits on a paper web browser window. [internet / online / search]
Credit: SolidColours / Getty Images

ASP.NET Core MVC 5 is a lightweight, open source framework built on top of the ASP.NET Core 5 runtime. ASP.NET Core 5 MVC provides support for request and response headers, which are collections of key-value pairs that are passed between the server and the client together with a request or response.

This article talks about how you can read request headers in ASP.NET Core 5 MVC, using the RequestHeaders class pertaining to Microsoft.AspNetCore.Http.Headers namespace. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create an ASP.NET Core 5 MVC project in Visual Studio 2019

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Following these steps will create a new ASP.NET Core 5 MVC project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window, select .NET 5.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here.
  10. Click Create.

A new ASP.NET Core 5 MVC project will be created. We’ll use this project to read with request headers in the subsequent sections of this article.

The IHeaderDictionary interface

In ASP.NET Core, HTTP request headers are represented as an instance of the IHeaderDictionary interface to ensure consistent storage and retrieval of header values. These headers, in turn, comprise a dictionary of key-value pairs. While the header keys in the request headers are stored as strings, the header values are represented as StringValues structs.

Extract all request headers in ASP.NET Core 5 MVC

You can take advantage of the Headers collection of the HttpRequest class to read data pertaining to one or more request headers in your application. The following code snippet illustrates how you can read data from the request headers, store it inside a dictionary, and then return the dictionary.

[HttpGet("GetAllHeaders")]
public ActionResult<Dictionary<string, string>> GetAllHeaders()
{
   Dictionary<string, string> requestHeaders =
      new Dictionary<string, string>();
   foreach (var header in Request.Headers)
   {
       requestHeaders.Add(header.Key, header.Value);
   }
   return requestHeaders;
}

To retrieve the value of a specific request header based on a key, you can use the following code snippet.

[HttpGet("GetHeaderData")]
public ActionResult<string> GetHeaderData(string headerKey)
{
   Request.Headers.TryGetValue(headerKey, out var headerValue);
   return Ok(headerValue);
}

When you invoke this action method from Postman, the output would appear as displayed in Figure 1 below.

request headers 01 IDG

Figure 1: Reading the request header value using the key passed as a query string.

Using the [FromQuery] and [FromHeader] attributes in ASP.NET Core 5 MVC

ASP.NET Core introduces the [FromQuery] and [FromHeader] attributes. While the former is used to pass data via query strings, the latter is used to pass data to the action methods of your controller using request headers.

The GetHeaderData method is analogous to the following code snippet. You can take advantage of the [FromQuery] attribute to rewrite the GetHeaderMethod as shown below.

[HttpGet("GetHeaderData")]
public ActionResult<string> GetHeaderData([FromQuery] string headerKey)
{
        Request.Headers.TryGetValue(headerKey, out var headerValue);
        return Ok(headerValue);
}

The [FromQuery] attribute enables you to get values from the query string. So, if you don’t specify the request header (as we did in the previous code example) but pass values using query strings, the action method will still work.

Now consider the following class.

public class Author
    {
        [FromHeader]
        public int Id { get; set; }
        [FromHeader]
        public string FirstName { get; set; }
        [FromHeader]
        public string LastName { get; set; }
    }

The [FromHeader] attribute in each of the properties of the Author class imply that each of these properties will be bound to the request header. The following code snippet illustrates how you can read the request header as an instance of the Author class.

[HttpGet("GetMessage")]
public ActionResult GetMessage([FromHeader] Author author)
{
  string message = $"The author details are:-nId : {author.Id}, " +
                               $"FirstName : {author.FirstName}, "+
                                $"LastName : {author.LastName}";
  return Ok(message);
 }

Figure 2 below shows how you can invoke this action method.

request headers 02 IDG

Figure 2: The [FromHeader] attribute at work.

You can also have a combination of attributes in an action method. The following code snippet illustrates how this can be achieved.

[HttpGet("GetTextMessage")]
public ActionResult GetTextMessage([FromBody] Author author, [FromHeader] string headerKey)
{
   Request.Headers.TryGetValue(headerKey, out var headerValue);
   string message = $"The author details are:-nId : {author.Id}, " +
                      $"FirstName : {author.FirstName}, " +
                      $"LastName : {author.LastName}, " +
                      $"Number of Books Authored : {headerValue}";
   return Ok(message);
}

Request headers are a great feature in ASP.NET Core that enable you to work with optional data represented as a collection of key-value pairs that can be transmitted back and forth between the client and server. The Request class provides access to metadata as well as headers of the HttpContext. However, if you would like to access request headers or HttpContext metadata in other classes in your application, you should take advantage of the IHttpContextAccessor interface.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author