web-api
  1. web-api-utilizing-frombody-attribute

Utilizing FromBody Attribute - (Web API FromBody and FromUri)

Web API is a popular tool for building RESTful APIs in .NET applications. When working with Web API, it's important to be able to parse and validate request data. In this tutorial, we'll discuss how to utilize the [FromBody] attribute to parse request data in a Web API controller.

Syntax

The syntax for using the [FromBody] attribute in a Web API controller action is as follows:

public IActionResult MyAction([FromBody] MyModel model)
{
    // process the model data
}

Here, MyModel is the data model that represents the request data.

Example

Suppose you have a Web API controller that accepts JSON data in a POST request. You can use the [FromBody] attribute to parse the JSON data into a data model as follows:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[HttpPost]
public IActionResult AddPerson([FromBody] Person person)
{
    // add the person to the database
    return Ok();
}

In this example, the AddPerson action accepts a Person object as input. The [FromBody] attribute indicates that the Person object should be parsed from the request body using JSON serialization.

Explanation

The [FromBody] attribute in Web API controllers is used to indicate that the parameter should be bound to the request body. This is useful when you want to parse JSON or XML data from a request body.

Use

The [FromBody] attribute is used when working with Web API controllers that accept data from a request body. This is typically used when working with JSON or XML data.

Important Points

Here are some important points to keep in mind when using the [FromBody] attribute in Web API controllers:

  • The [FromBody] attribute can only be applied to a single parameter per action.
  • The [FromBody] attribute is used to parse JSON or XML data from a request body.
  • The data model used with the [FromBody] attribute should match the structure of the request data.

Summary

In this tutorial, we discussed how to utilize the [FromBody] attribute in Web API controllers. We covered the syntax, example, explanation, use, and important points of parsing request data in a Web API controller using the [FromBody] attribute. By using this attribute, you can easily parse and validate request data in your Web API controllers.

Published on: