ASP.NET Web API-FormBody vs FormUri Attribute


In this article we will see the difference between two attributes in ASP.NET Web API FormBody and FormUri with example.

ASP.NET web API FormBody vs FormUri Attribute

1. [FromBody] Attribute

The [FromBody] attribute is used to bind complex types or multiple parameters from the request body. It is typically used when sending data in JSON or XML format. When a parameter is decorated with [FromBody], Web API uses the configured media-type formatter to deserialize the request body into the specified parameter type.

Example

[HttpPost]
public IHttpActionResult CreateBook([FromBody] bookDto bookDto)
{
     // Process the bookDto received from the request body
    return Ok();
}

In the above example, the CreateBook action method expects a complex type BookDto to be sent in the request body as JSON or XML. The [FromBody] attribute instructs Web API to bind the request body to the bookDto parameter.

2. [FromUri] Attribute

The [FromUri] attribute is used to bind simple types or single parameters from the URI or query string. By default, simple types are bound from the URI or query string, so the [FromUri] attribute is not required in most cases.

Example

[HttpGet]
public IHttpActionResult Getbook([FromUri] int id)
{
    // Retrieve the book with the specified id from the database
    return Ok(book);
}

In the above example, the Getbook action method expects a simple type int to be sent as part of the URI or query string. The [FromUri] attribute is used to explicitly indicate that the id parameter should be bound from the URI or query string.

Difference Between ASP.NET Web API [FromBody] and [FromUri] Attribute

S.No. [FromBody] Attribute [FromUri] Attribute
1 The [FromBody] attribute is used to bind complex types or multiple parameters from the request body.  The [FromUri] attribute is used to bind simple types or single parameters from the URI or query string.
2 It is typically used when sending data in JSON or XML format.When a parameter is decorated with [FromBody], Web API uses the configured media-type formatter to deserialize the request body into the specified parameter type. By default, simple types are bound from the URI or query string  so the [FromUri] attribute is not required in most cases.
[HttpPost]
public IHttpActionResult CreateBook([FromBody] bookDto bookDto)
{
     // Process the bookDto received from the request body
    return Ok();
}
[HttpGet]
public IHttpActionResult Getbook([FromUri] int id)
{
    // Retrieve the book with the specified id from the database
    return Ok(book);
}

Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#