ASP.Net Web API is a lightweight framework that can be used for building RESTful HTTP services. When working with controller methods in Web API, you will often need to pass parameters to those methods. A “parameter” here simply refers to the argument to a method, while “parameter binding” refers to the process of setting values to the parameters of the Web API methods.
Note that there are two ways in which Web API can bind parameters: model binding and formatters. Model binding is used to read from the query string, while formatters are used to read from the request body. You can also use type converters to enable Web API to treat a class as a simple type and then bind the parameter from the URI. To do this, you would need to create a custom TypeConverter. You can also create a custom model binder by implementing the IModelBinder interface in your class and then implementing the BindModel method. For more on type converters and model binders, .
Now, in order to bind parameters, Web API follows this rule: For simple types, Web API tries to get the value from the URI, and for complex types, Web API tries to get the value from the request body. The simple types here refer to both the .Net primitive types—int, bool, double, float, and so on—and to other types that include TimeSpan, DateTime, Guid, decimal, and string. It also includes any type for which a type converter is available that can convert from a string. In the next section we’ll explore the [FromBody] and [FromUri] attributes used to bind values from the request body and URI respectively.
When to use [FromBody] and [FromUri] in Web API
If you’ve been using Web API for some time, you may be familiar with the [FromBody] and [FromUri] attributes. The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.