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

Maria J. Danford

ASP.Internet Main MVC five is a lightweight, open up source framework designed on top of the ASP.Internet Main five runtime. ASP.Internet Main five MVC supplies help for request and response headers, which are collections of key-worth pairs that are passed between the server and the shopper with each other with a request or response.

This short article talks about how you can read request headers in ASP.Internet Main five MVC, utilizing the RequestHeaders course pertaining to Microsoft.AspNetCore.Http.Headers namespace. To work with the code illustrations presented in this short article, you really should have Visual Studio 2019 put in in your technique. If you don’t previously have a copy, you can download Visual Studio 2019 in this article.

Generate an ASP.Internet Main five MVC undertaking in Visual Studio 2019

1st off, let us create an ASP.Internet Main undertaking in Visual Studio 2019. Following these steps will create a new ASP.Internet Main five MVC undertaking in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on on “Create new undertaking.”
  3. In the “Create new project” window, decide on “ASP.Internet Main World wide web App (Model-See-Controller)” from the listing of templates shown.
  4. Click on Following.
  5. In the “Configure your new project” window, specify the identify and locale for the new undertaking.
  6. Optionally check the “Place remedy and undertaking in the identical directory” check box, depending on your choices.
  7. Click on Following.
  8. In the “Additional Information” window, decide on .Internet five. as the concentrate on framework from the drop-down listing at the top. Leave the “Authentication Type” as “None” (default).
  9. Make certain that the check bins “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we will not be utilizing any of individuals features in this article.
  10. Click on Generate.

A new ASP.Internet Main five MVC undertaking will be produced. We’ll use this undertaking to read with request headers in the subsequent sections of this short article.

The IHeaderDictionary interface

In ASP.Internet Main, HTTP request headers are represented as an instance of the IHeaderDictionary interface to ensure reliable storage and retrieval of header values. These headers, in change, comprise a dictionary of key-worth pairs. Although 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.Internet Main five MVC

You can acquire edge of the Headers selection of the HttpRequest course to read knowledge pertaining to a person or additional request headers in your software. The following code snippet illustrates how you can read knowledge from the request headers, store it inside a dictionary, and then return the dictionary.

[HttpGet("GetAllHeaders")]
public ActionResult> GetAllHeaders()

   Dictionary requestHeaders =
      new Dictionary()
   foreach (var header in Ask for.Headers)
  
       requestHeaders.Increase(header.Important, header.Benefit)
  
   return requestHeaders

To retrieve the worth of a distinct request header centered on a key, you can use the following code snippet.

[HttpGet("GetHeaderData")]
public ActionResult GetHeaderData(string headerKey)

   Ask for.Headers.TryGetValue(headerKey, out var headerValue)
   return Alright(headerValue)

When you invoke this motion method from Postman, the output would show up as shown in Figure 1 down below.

request headers 01 IDG

Figure 1: Examining the request header worth utilizing the key passed as a question string.

Utilizing the [FromQuery] and [FromHeader] attributes in ASP.Internet Main five MVC

ASP.Internet Main introduces the [FromQuery] and [FromHeader] attributes. Although the former is used to move knowledge by using question strings, the latter is used to move knowledge to the motion methods of your controller utilizing request headers.

The GetHeaderData method is analogous to the following code snippet. You can acquire edge of the [FromQuery] attribute to rewrite the GetHeaderMethod as proven down below.

[HttpGet("GetHeaderData")]
public ActionResult GetHeaderData([FromQuery] string headerKey)

        Ask for.Headers.TryGetValue(headerKey, out var headerValue)
        return Alright(headerValue)

The [FromQuery] attribute permits you to get values from the question string. So, if you don’t specify the request header (as we did in the prior code illustration) but move values utilizing question strings, the motion method will nonetheless work.

Now think about the following course.

public course Creator
   
        [FromHeader]
        public int Id get established
        [FromHeader]
        public string FirstName get established
        [FromHeader]
        public string LastName get established
   

The [FromHeader] attribute in just about every of the attributes of the Creator course suggest that just about every of these attributes will be certain to the request header. The following code snippet illustrates how you can read the request header as an instance of the Creator course.

[HttpGet("GetMessage")]
public ActionResult GetMessage([FromHeader] Creator creator)

  string information = $"The creator particulars are:-nId : creator.Id, " +
                               $"FirstName : creator.FirstName, "+
                                $"LastName : creator.LastName"
  return Alright(information)
 

Figure 2 down below reveals how you can invoke this motion method.

request headers 02 IDG

Figure 2: The [FromHeader] attribute at work.

You can also have a mixture of attributes in an motion method. The following code snippet illustrates how this can be attained.

[HttpGet("GetTextMessage")]
public ActionResult GetTextMessage([FromBody] Creator creator, [FromHeader] string headerKey)

   Ask for.Headers.TryGetValue(headerKey, out var headerValue)
   string information = $"The creator particulars are:-nId : creator.Id, " +
                      $"FirstName : creator.FirstName, " +
                      $"LastName : creator.LastName, " +
                      $"Quantity of Textbooks Authored : headerValue"
   return Alright(information)

Ask for headers are a good function in ASP.Internet Main that help you to work with optional knowledge represented as a selection of key-worth pairs that can be transmitted back and forth between the shopper and server. The Ask for course supplies entry to metadata as perfectly as headers of the HttpContext. Even so, if you would like to entry request headers or HttpContext metadata in other classes in your software, you really should acquire edge of the IHttpContextAccessor interface.

Copyright © 2021 IDG Communications, Inc.

Next Post

Computer Technology Major

Students have opportunities to explore and navigate the faculty setting, develop/reinforce tutorial expertise and take part in service learning alternatives. Students are encouraged to establish significant connections with faculty, workers and peers. The course promotes the development of plans for ongoing growth and involvement at school and in the RIT/NTID […]

Subscribe US Now