Model Binding using FromBody in ASP.NET Core MVC

Model Binding using FromBody in ASP.NET Core MVC

In this article, I will discuss How to Use FromBody to Perform Model Binding in ASP.NET Core MVC with Examples. Please read our previous article discussing FromHeader in ASP.NET Core MVC.

Model Binding using FromBody in ASP.NET Core MVC

Model binding in ASP.NET Core MVC maps incoming HTTP request data to action method parameters. When data is sent in the body of an HTTP request (typically for POST, PUT, and PATCH methods), it usually comes as JSON or XML. In such cases, you need to use the FromBody attribute to bind this incoming data to a parameter in your action method. If you go to the definition of FromBodyAttribute, you will see the following signature.

Model Binding using FromBody in ASP.NET Core MVC

The FromBodyAttribute specifies that a parameter or property should be bound using the request body.

Example to Understand FromBodyAttribute in ASP.NET Core MVC:

First, create a class file with the name User.cs within the Models folder, and then copy and paste the following code. This is a simple model that represents a user.

namespace ModelBindingDemo.Models
{
    public class User
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public int Age { get; set; }
        public string? Mobile { get; set; }
    }
}

Create a controller action and use the FromBody attribute to bind the incoming request body to your model. Create a controller named UsersController and then copy and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
using ModelBindingDemo.Models;

namespace ModelBindingDemo.Controllers
{
    public class UsersController : Controller
    {
        [Route("users/create")]
        [HttpPost]
        public IActionResult Create([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Handle the user data: save it to a database, perform some operations, etc.

            // Often, you might return the created entity or just a success message.
            return Ok(user);  
        }
    }
}
Making a Request:

Clients can then send a POST request with a JSON body to the /users/create endpoint:

{
    "Id": 10,
    "Name": "Kumar",
    "Age": 30,
    "Mobile":"1234567890"
}

The FromBody attribute will take this JSON data, attempt to deserialize it into a User object and provide it to your action method as the user parameter.

Points to Remember:
  • Ensure you have a suitable JSON serializer configured for your application. For many applications in ASP.NET Core, the default JSON serializer (like Newtonsoft.Json in older versions or System.Text.Json in newer versions) is used.
  • If deserialization fails (e.g., the provided JSON doesn’t match the User structure or contains invalid data), the model binding will mark the model as invalid. This is why you check ModelState.IsValid in your action method. If it’s false, it means something went wrong with the binding.
  • You can return a bad request or any other appropriate response when the model state is invalid. The ModelState will contain error messages about what went wrong, which can be useful for debugging or informing clients about the nature of the error.
  • In ASP.NET Core 3.x and later, you no longer need to specify [FromBody] for complex types; it’s inferred by default. However, it’s still a good practice to include it for clarity.
When to Use FromBody Attribute in ASP.NET Core?

In ASP.NET Core, the FromBody attribute binds action method parameters from the request body. It’s especially useful when dealing with HTTP methods like POST, PUT, and PATCH, where significant data is sent in the request body. Here’s when we would typically use the FromBody attribute:

RESTful APIs:

When creating (POST) or updating (PUT, PATCH) resources, you often send the entire resource or changes in the request body. The FromBody attribute allows the automatic deserialization of the incoming request body to a .NET object.

[HttpPost]
public IActionResult Create([FromBody] Product product)
{
    // Add product to database or process it
}
Complex Data Types:

For sending complex objects, arrays, or other structured data. Query strings (with FromQuery) are better suited for simple values or filtering criteria, while the request body can accommodate more structured and comprehensive data.

JSON or XML Payloads:

Modern web APIs often communicate using JSON or XML payloads. Clients send this data in the request body, and the FromBody attribute tells the ASP.NET Core framework to use input formatters to deserialize this data into the corresponding .NET types.

Avoiding Length Limitations:

URLs have length limits. When you have a large amount of data to send, sending it in the body is more suitable than as a query string or as part of the URL.

Increased Data Privacy:

While both the body and URL are encrypted in HTTPS requests, data in the URL can be stored in browser history, server logs, or analytics tools. It’s often better to send more sensitive data in the body.

Working with Modern Frontend Frameworks:

If you’re building an application with modern frontend frameworks like React, Angular, or Vue.js, sending data via the request body (often in JSON format) is the standard practice.

When Not to Use:
  • Simple Data Types in GET Requests: For simple data types, especially in GET requests, you’d use the query string or route data rather than the request body.
  • URL Identifiers: If you’re trying to capture resource identifiers or other data that are part of the URL, you should use FromRoute or FromQuery.

So, FromBody is essential when dealing with rich data sent in the request body, especially in web APIs. It allows you to work effectively with structured data and is crucial for many CRUD operations in modern web development.

In the next article, I will discuss Complex Type Model Binding in ASP.NET Core MVC with Examples. In this article, I explain How to use FromBody to Perform Model Binding in ASP.NET Core MVC with Examples. I hope you enjoy this FromBody in ASP.NET Core MVC article.

Leave a Reply

Your email address will not be published. Required fields are marked *