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. 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. 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). 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. 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. 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. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos