What is the difference between FromBody and FromUri attributes in C# ASP.NET
WebAPI?


When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.

In order to bind a model (an action parameter), that would normally default to a formatter, from the URI we need to decorate it with [FromUri] attribute. FromUriAttribute simply inherits from ModelBinderAttribute, providing us a shortcut directive to instruct Web API to grab specific parameters from the URI using the ValueProviders defined in the IUriValueProviderFactory. The attribute itself is sealed and cannot be extended any further, but you add as many custom IUriValueProviderFactories as you wish.

The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter. When [FromBody] is applied to a complex type parameter, any binding source attributes applied to its properties are ignored.

Example for FromUri Attribute

Example

using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IEnumerable<string> Get([FromUri] string id, [FromUri] string name){
         return new string[]{
            $"The Id of the Student is {id}",
            $"The Name of the Student is {name}"
         };
      }
   }
}

For the above example let us pass the value of the id and name in the URI to populate to their corresponding variable in the Get method.

http://localhost:58174/api/demo?id=1&name=Mark

Output

The output of the above code is

Example for FromBody Attribute

Example

Let us create a Student model which has the below properties.

namespace DemoWebApplication.Models{
   public class Student{
      public int Id { get; set; }
      public string Name { get; set; }
   }
}

Controller Code

Example

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IEnumerable<string> Get([FromBody] Student student){
         return new string[]{
            $"The Id of the Student is {student.Id}",
            $"The Name of the Student is {student.Name}"
         };
      }
   }
}

For the above example the value for the student is passed in the request body and it is mapped to corresponding property of the Student object. Below is the request and response using Postman.

Updated on: 19-Aug-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements