FromHeader Attribute in Asp.net Core

FromHeader Attribute in Asp.net Core
FromHeader attribute is used to instruct the model binder to fetch values for action method parameters directly from HTTP request headers. HTTP headers are key-value pairs that provide metadata about the request, such as the client’s browser type (User-Agent), accepted content types (Accept), and authorization tokens.
 
How [FromHeader] Works
Header Identification: When a request arrives, ASP.NET Core’s model binding system identifies action parameters marked with the [FromHeader] attribute.
Header Extraction: It then examines the request headers to locate the headers that match the names specified in the [FromHeader] attribute.
Value Assignment: If the matching header is found, its value is assigned to the corresponding action parameter. If the header is not present or its value cannot be converted to the parameter’s type, the model state will be marked as invalid.
 
 
Code
// HomeController.cs
[Route(“register”)]
public IActionResult Index(Person person, [FromHeader(Name = “User-Agent”)] string UserAgent)
{
    // … (model validation logic) …
 
    return Content($”{person}, {UserAgent}”); // Include User-Agent in the response
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply