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


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.

Copyright © 2021 IDG Communications, Inc.



Source link