What advantage do we get if we specify Frombody and FromUri attribute in web api? - asp.net-web-api

What are the benefits/advantages we get if we specify this frombody and fromuri attribute in web-api?

Web API parameter binding expects simple type values coming from query string, and complex types like array coming from the body of the request. Hence if you have an action method like this one:
public class EmployeesController : ApiController
{
public IHttpActionResult Get(int id, string[] names)
{
return Ok("Method Called");
}
}
,and if you want to formulate your request like this:
/api/employees?id=1&names=Fred&names=Anna
, then without [FromUri] the value of "names" parameter won't be bound.
So your API method must be like this in order to get all parameters bound:
public IHttpActionResult Get(int id,[FromUri] string[] names)
{
return Ok("Method Called");
}
More from here: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Related

web api controller action methods

I am trying to get a web api call to work: I want to submit an email address and then on the server, the method will validate and return null or a message.
This is what I tried:
[Post]
public string validate(string email) {
return this._contextProvider.ValidateEmail(email);
}
However, I get this message returned to the client: No HTTP resource was found that matches the request URI 'https://localhost:44300/breeze/data/validate
The payload looks like this: {email: "Greg#gmail.com"}
The problem, it turns out, was the parameter binding.
In the Web API, binding is handling differently than MVC. By default, simple types are extracted from the URI, not the body. Complex types are extracted from the body of the message.
I then added the [FromBody] Attribute to the Action Method, and it then found the action method. But alas, the email parameter was null.
public string validate([FromBody]string email) {
return this._contextProvider.ValidateEmail(email);
}
Turns out when using this trick, the body must NOT be json, but constructed like a querystring - email=greg#gmail.com. I didn't want do do that, so ended up creating a class to accept the parameter, and that worked as expected.
public class ParameterizedAction {
public string Parameter { get; set; }
}
public string validate(ParameterizedAction arg) {
return this._contextProvider.ValidateEmail(arg.Parameter);
}
This article has more info: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
as well as this one: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Why do we have to specify FromBody and FromUri?

Why are the FromBody and FromUri attributes needed in ASP.NET Web API`?
What are the differences between using the attributes and not using them?
When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.
By default, Web API uses the following rules to bind parameters:
If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
For complex types, Web API tries to read the value from the message body, using a media-type formatter.
So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.
So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.
There is a lot more information on the web if you google "web api parameter binding".
The default behavior is:
If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.
For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.
So, if you have:
a primitive type in the URI, or
a complex type in the body
...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).
But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)
Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)
Primitive types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post([FromBody]int id)
{
}
// api/users/id
public HttpResponseMessage Post(int id)
{
}
}
Complex types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post(User user)
{
}
// api/users/user
public HttpResponseMessage Post([FromUri]User user)
{
}
}
This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:
public class MyModel
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
// model.MyProperty;
// model.MyProperty2;
}
From Microsoft's documentation for parameter binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header
to select a formatter. In this example, the content type is
"application/json" and the request body is a raw JSON string (not a
JSON object). At most one parameter is allowed to read from the
message body.
This should work:
public HttpResponseMessage Post([FromBody] string name) { ... }
This will not work:
// Caution: This won't work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a
non-buffered stream that can only be read once.
Just addition to above answers ..
[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring
For Ex..
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
[Route("{Latitude}/{Longitude}")]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Can be called like:
http://localhost/api/values/47.678558/-122.130989
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
At most one parameter is allowed to read from the message body. So this will not work:
// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
Please go through the website for more details:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Why does parameter binding work differently when there is an argument in the route template, e.g. /route/{id}?

I've found what seems to be an inconsistent behavior in ASP.NET Web API. Say I have the following controller:
public class FooController: ApiController
{
[HttpGet, Route("foo")]
public IHttpActionResult GetFoo([FromUri]Bar request)
{
}
[HttpGet, Route("foo/{id}")]
public IHttpActionResult GetFoo(int id, [FromUri]Bar request)
{
}
}
If I send a GET request to /foo, with no query string parameters, the first method will be executed and its request argument will be null - which makes sense. But that's not what happens when I send a request to foo/1. In this case, I'd expect only the id parameter to be filled with 1, but it turns out that both arguments are initialized.
Why is that so? If that's by design, what could I do in order to "normalize" that behavior, i.e., make the request parameter in both methods to be either null or initialized?

How to send a GUID to a web api webservice

I am extending ApiController for a webservice.
The service takes a GUID as its only parameter. This is the url that I type in
/api/texts/2ADEA345-7F7A-4313-87AE-F05E8B2DE678
However, the Guid never reaches the Get method.
If I set it to object
public Object Get(Object userId)
the method fires, but userid is null.
If i set it to guid
public Object Get(Guid? userId)
I get the error
No action was found on the controller 'texts' that matches the request.
Does anyone have a sample that could help me?
I suppose that you are using the default route in which the pattern is:
api/{controller}/{id}
So try naming your parameter accordingly:
public TextsController: ApiController
{
public HttpResponseMessage Get(Guid? id)
{
...
}
}
Now the /api/texts/2ADEA345-7F7A-4313-87AE-F05E8B2DE678 url should hit the Get action on the TextsController and populate the id parameter.

read Asp.Net Web api GET values from url

I am trying to map /{Controller}/{Variable1}/{Variable2}/{Variable3} to a GET method in controller
public TestController{
public ActionResult Get([FromUrl] Entity instance){}
}
So I need to map variables to the entity.
To put it into an example
/Product/{category}/{filter1}/{filter2}/
Entity
public class ProductSearchRequest
{
public string Category{get;set;}
public string filter1 {get;set;}
public string filter2 {get;set;}
}
Controller
public ProductController: Controller {
public ActionResult GET([FromUri] ProductSearchRequest productSearchRequest){
}
}
[EDITED]
Had to do following changes to get this working
Instead of RouteCollection.MapHttpRoute use HttpConfiguration.Routes.MapHttpRoute as this is API routing not MVC routing.
Inherit controller from ApiController rather than Controller which I was before.
Basically you are not going to be able to do that. Complex types are not compatible with the routing mechanism.
Take a read of this article. But this paragraph explains why the routing mechanism cannot do what you are asking.
A complex type can only bind to the URI through a custom binding. But
in that case, the framework cannot know in advance whether the
parameter would bind to a particular URI. To find out, it would need
to invoke the binding. The goal of the selection algorithm is to
select an action from the static description, before invoking any
bindings. Therefore, complex types are excluded from the matching
algorithm.
Therefore the basic rule is:
For every parameter of the action, if the parameter is taken from the
URI, then the parameter name must be found either in the route
dictionary or in the URI query string. (Optional parameters and
parameters with complex types are excluded.)
Which means you need to define your action like so:
public ActionResult GET(string Category, string filter1, string filter2){
}
And your route template:
/{controller}/{category}/{filter1}/{filter2}/

Resources