Back to: ASP.NET Core Tutorials For Beginners and Professionals
Model Binding using FromHeader in ASP.NET Core MVC
I will discuss How to Use FromHeader to Perform Model Binding in ASP.NET Core MVC with Examples in this article. Please read our previous article discussing FromRoute in ASP.NET Core MVC.
Model Binding using FromHeader in ASP.NET Core MVC
In ASP.NET Core MVC, the FromHeader attribute is used to specify that a parameter should be bound using data from the header of the HTTP request. Headers of an HTTP Request provide a way to send additional information about a request or response. This includes common standard headers (e.g., User-Agent, Content-Type), and you can also pass custom headers.
The FromHeader attribute is especially useful when working with API endpoints that require specific header data to process a request, such as authentication tokens or custom client metadata. If you go to the definition of FromBodyAttribute, you will see the following signature.
The FromHeaderAttribute specifies that a parameter or property should be bound using the request headers.
Example to understand FromHeaderAttribute in ASP.NET Core MVC:
Let’s assume we have an API endpoint where the client provides a version number through a custom header, and based on this version, the server might change its response. So, create a controller named UsersController and copy and paste the following code into it.
using Microsoft.AspNetCore.Mvc; namespace ModelBindingDemo.Controllers { public class UsersController : Controller { [Route("users/data")] [HttpGet] public IActionResult GetUsers([FromHeader(Name = "X-Api-Version")] string apiVersion) { if (string.IsNullOrEmpty(apiVersion)) { return BadRequest("X-Api-Version header is required."); } if (apiVersion == "1.0") { // Return data specific to version 1.0 return Ok(new { version = "1.0", data = "Data for v1.0" }); } else if (apiVersion == "2.0") { // Return data specific to version 2.0 return Ok(new { version = "2.0", data = "Data for v2.0" }); } else { return BadRequest($"Unsupported API version: {apiVersion}"); } } } }
Request with Headers:
Clients can request the /users/data endpoint and set the X-Api-Version header to 1.0 or 2.0 to fetch version-specific data.
Points to Remember:
- The Name property in the FromHeader attribute is used to specify the header’s name from which the data should be bound. If the parameter name matches the header name, the Name property isn’t strictly necessary, but it’s a good practice to include it for clarity.
- Always validate incoming header data. Clients can manipulate headers, so don’t trust them implicitly. In this example, we perform basic validation by checking for null, empty, and known versions.
When to use FromHeader Attribute in ASP.NET Core MVC?
In ASP.NET Core MVC, the FromHeader attribute binds action method parameters to specific HTTP header values. Here are scenarios in which you might use the FromHeader attribute:
Authentication & Authorization:
The Authorization header is often used to pass tokens (like JWTs) or credentials to the server.
[HttpGet] public IActionResult Get([FromHeader(Name = "Authorization")] string token) { // Validate token and proceed }
Content Negotiation:
Clients can use the Accept header to specify the expected media type (e.g., application/json, text/xml). The server can then use this header to determine how to format the response. Similarly, the Content-Type header can inform the server about the data format in the request body.
Caching Control:
Headers like If-Modified-Since or If-None-Match can be used for conditional requests. The server can check these headers and decide whether to send a full response or a 304 Not Modified status.
Localization:
The Accept-Language header can specify the client’s language preferences. Based on this, the server can return localized content.
[HttpGet] public IActionResult GetLocalizedContent([FromHeader(Name = "Accept-Language")] string language) { // Return content based on the provided language preference }
Custom Headers for Business Logic:
Sometimes, apps define custom headers for specific business requirements. For instance, an X-User-Tier header could denote the subscription tier of the user, affecting the kind of data or features available to them.
Rate Limiting:
If you’re implementing rate limiting, headers like X-RateLimit-Limit and X-RateLimit-Remaining can be utilized to communicate rate limit details back to the client.
Debugging or Diagnostics:
Some applications use headers for diagnostics or tracing. For example, a header might contain a trace ID propagated through various microservices to track a request.
When Not to Use:
- Regular Payload Data: Headers are not meant for standard request payload data. Use FromBody, FromQuery, or FromRoute for that.
- Sensitive Data: It’s best to avoid sending sensitive data in headers, especially if unnecessary. While headers are part of the encrypted content in HTTPS traffic, they can be logged in server logs or exposed in other parts of the processing pipeline.
So, FromHeader provides a way to access specific HTTP headers and can be vital for certain scenarios, especially around authentication, content negotiation, and other HTTP-specific functionalities. However, it’s important to use it judiciously and avoid overloading headers with unnecessary data.
In the next article, I will discuss How to Use FromBody to Perform Model Binding in ASP.NET Core MVC with Examples. In this article, I explain How to Use FromHeader to Perform Model Binding in ASP.NET Core MVC with Examples. I hope you enjoy this FromHeader in ASP.NET Core MVC article.