FromBody Attribute in Asp.net Core

FromBody Attribute in Asp.net Core
FromBody attribute is a crucial tool in ASP.NET Core MVC’s model binding arsenal, designed to handle scenarios where the incoming data is contained within the body of an HTTP request. This is especially common when working with APIs and modern web applications that frequently exchange data in formats like JSON or XML.
 
How It Works
Request Body Identification: When a request arrives, the model binding middleware examines the Content-Type header to determine the format of the data in the request body. Typically, this is either application/json for JSON data or application/xml for XML data.
Input Formatter Selection: Based on the Content-Type, the middleware selects an appropriate input formatter. Input formatters are responsible for deserializing the raw request body into a format that the model binder can understand.
Model Binding: The model binder takes the deserialized data and attempts to map it to the properties of your model class. This mapping is typically done based on property names, but you can customize it using various model binding attributes.
Validation: After binding, the model undergoes validation to ensure it adheres to the rules defined by data annotations or custom validation logic.
 
Benefits of FromBody
Complex Data Handling: Easily bind complex objects with nested properties from JSON or XML payloads.
Separation of Concerns: The input formatter handles deserialization, keeping your controller actions clean.
API-Friendly: Aligns well with RESTful API practices, where data is often transmitted in the request body.
 
 
Code
// HomeController.cs
[Route(“register”)]
// Example JSON: { “PersonName”: “William”, “Email”: “william@example.com”, “Phone”: “123456”, “Password”: “william123”, “ConfirmPassword”: “william123” }
public IActionResult Index([FromBody] Person person)
{
    if (!ModelState.IsValid)
    {
        // … (handle validation errors) …
    }
 
    return Content($”{person}”);
}
In this code:
[FromBody] Attribute: The [FromBody] attribute on the person parameter instructs the model binder to look for the data in the request body.
JSON Deserialization: If the request has a Content-Type of application/json, the built-in JSON input formatter will deserialize the JSON data in the request body into a Person object.
Model Validation: The ModelState.IsValid check ensures the deserialized Person object meets your validation criteria.
Successful Response: If the model is valid, the Content result returns a string representation of the Person object.
 
Important Considerations
Single [FromBody] Parameter: ASP.NET Core model binding allows only one parameter per action method to be decorated with [FromBody]. This is because the request body is typically a single stream of data.
Content-Type: The Content-Type header of the request must match the expected format (e.g., application/json) for the correct input formatter to be used.
Security: Always validate and sanitize data from the request body to protect against vulnerabilities like overposting and injection attacks.

Comments

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

Leave a Reply