Oct 18, 2012

Web API-My First Look At Parameter Binding


This takes http request and convert it into .Net type which is passed as action parameter. Without this every action would have to take request message and manually extract parameter.

WebAPI uses model binding (same as MVC ValueProviders) to read from the query string and Formatters to read from the body. Formatters gets the list of formatters from the HttpConfiguration, and then uses the request’s content-type to select an appropriate formatter. WebAPI has some default formatters-JSON.Net.

Following code show few configuration which can be done around JsonFormatter
//config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; //Use this for DataContractJsonSerializer
config.Formatters.JsonFormatter.Indent = true;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();

If the parameter has no attribute on it, then the decision is made purely on the parameter’s .NET type. Simple types uses model binding. Complex types uses the formatters.

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once. This means if formatter uses this for binding model, then you cannot access request content (Request.Content) inside action. This also means you cannot have two action parameters to be binded from body. Something like this will throw exception as "Can't bind multiple parameters ('body' and 'body1') to the request's content.",

public HttpResponseMessage PostProduct([FromBody] string body, [FromBody] string body1)

This behavior is different than Mcv, in which case model binding can repeatedly search through value providers.


No comments:

Post a Comment