How to Read Request Headers in ASP.NET Core
By FoxLearn 2/3/2025 7:52:01 AM 130
The IHeaderDictionary Interface
In ASP.NET Core, HTTP request headers are stored using the IHeaderDictionary
interface. This ensures consistent management of header values, where the header keys are stored as strings, and the values are represented as StringValues
structs.
Extracting All Request Headers in ASP.NET Core MVC
To access request headers in your application, you can use the Headers
collection of the HttpRequest
class.
For example, how to read all the request headers, store them in a dictionary, and 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 by its 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 invoking this action through Postman or another API testing tool, you would see the specific header value corresponding to the key provided in the query string.
Using [FromQuery]
and [FromHeader]
Attributes in ASP.NET Core MVC
ASP.NET Core provides the [FromQuery]
and [FromHeader]
attributes, which allow you to bind data to your controller methods directly from the query string or request headers, respectively.
For example, how to rewrite the previous GetHeaderData
method using the [FromQuery]
attribute:
[HttpGet("GetHeaderData")] public ActionResult<string> GetHeaderData([FromQuery] string headerKey) { Request.Headers.TryGetValue(headerKey, out var headerValue); return Ok(headerValue.ToString()); }
The [FromQuery]
attribute allows you to extract values from the query string. If the header isn't present and values are passed in the query string, the method will still work as intended.
Now, let’s take a look at another example where we create a class representing a User
and bind its properties from the request headers.
public class User { [FromHeader] public string UserId { get; set; } [FromHeader] public string UserName { get; set; } }
In this case, each property of the User
class will be populated by the corresponding request header.
For example, how to read those header values into an instance of User
:
[HttpGet("GetUserInfo")] public ActionResult GetUserInfo([FromHeader] User user) { string message = $"User Information: \nUserId: {user.UserId}, " + $"UserName: {user.UserName}"; return Ok(message); }
This example shows how request headers can be directly mapped to a complex object.
Combining Attributes for Flexible Binding
You can also combine attributes to bind both request body and headers in the same action method. Below is an example where we use [FromBody]
to extract data from the request body, while [FromHeader]
retrieves header data.
[HttpGet("GetCombinedInfo")] public ActionResult GetCombinedInfo([FromBody] User user, [FromHeader] string authToken) { string message = $"User Information: \nUserId: {user.UserId}, " + $"UserName: {user.UserName}, " + $"AuthToken: {authToken}"; return Ok(message); }
In this case, the method reads both the User
data from the request body and the authToken
from the request headers. It then combines the values into a single message.
Request headers in ASP.NET Core are a fundamental feature for passing optional metadata between the client and server. By leveraging the IHeaderDictionary
interface, you can easily read, store, and manipulate request headers. The Request
class provides direct access to these headers, and the [FromQuery]
and [FromHeader]
attributes make it easy to bind header data to your controller methods.
- Options Pattern In ASP.NET Core
- Implementing Rate Limiting in .NET
- IExceptionFilter in .NET Core
- Repository Pattern in .NET Core
- CRUD with Dapper in ASP.NET Core
- How to Implement Mediator Pattern in .NET
- How to use AutoMapper in ASP.NET Core
- How to fix 'asp-controller and asp-action attributes not working in areas'