Web API 2 Exploring Parameter Binding

This article demonstrates how to call or map Web API methods with different types of parameters using XML, Json and Urlencoded formats. It shows how simple parameters, objects parameters and array parameters can be sent either in the body of the Http request or in the Url itself. This all works per default in Web API and if that’s not enough, you can customize it yourself.

code: https://github.com/damienbod/WebApiParameters

Simple Parameters

Example 1: Sending a simple parameter in the Url

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
  // http://localhost:49407/api/values/example1?id=2
  [Route("example1")]
  [HttpGet]
  public string Get(int id)
  {
     return "value";
  }
}

Example 2: Sending simple parameters in the Url

// http://localhost:49407/api/values/example2?id1=1&id2=2&id3=3
[Route("example2")]
[HttpGet]
public string GetWith3Parameters(int id1, long id2, double id3)
{
    return "value";
}

Example 3: Sending simple parameters using attribute routing

// http://localhost:49407/api/values/example3/2/3/4
[Route("example3/{id1}/{id2}/{id3}")]
[HttpGet]
public string GetWith3ParametersAttributeRouting(int id1, long id2, double id3)
{
   return "value";
}

Example 4: Sending an object in the Url

// http://localhost:49407/api/values/example4?id1=1&id2=2&id3=3
[Route("example4")]
[HttpGet]
public string GetWithUri([FromUri] ParamsObject paramsObject)
{
  return "value:" + paramsObject.Id1;
}

Example 5: Sending an object in the Request body

[Route("example5")]
[HttpPost]
public string GetWithBody([FromBody] ParamsObject paramsObject)
{
  return "value:" + paramsObject.Id1;
}

Calling the method using Urlencoded in the body:

User-Agent: Fiddler
Host: localhost:49407
Content-Length: 32
Content-Type: application/x-www-form-urlencoded

id1=1&id2=2&id3=3

WebApiParams_01

Calling the method using Json in the body:

User-Agent: Fiddler
Host: localhost:49407
Content-Length: 32
Content-Type: application/json

{ "Id1" : 2, "Id2": 2, "Id3": 3}

WebApiParams_02

Calling the method using XML in the body

This requires extra code in the Global.asax

protected void Application_Start()
{
   var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
   xml.UseXmlSerializer = true;

The client request is as follows:

User-Agent: Fiddler
Content-Type: application/xml
Host: localhost:49407
Content-Length: 65

<ParamsObject><Id1>7</Id1><Id2>8</Id2><Id3>9</Id3></ParamsObject>

WebApiParams_03

Arrays and Lists

Example 6: Sending a simple list in the Url

// http://localhost:49407/api/values/example6?paramsObject=2,paramsObject=4,paramsObject=9
[Route("example6")]
[HttpGet]
public string GetListFromUri([FromUri] List<int> paramsObject)
{
  if (paramsObject != null)
  {
	return "recieved a list with length:" + paramsObject.Count;
  }

  return "NOTHING RECIEVED...";
}

Example 7: Sending an object list in the Body

// http://localhost:49407/api/values/example8
[Route("example8")]
[HttpPost]
public string GetListFromBody([FromBody] List<ParamsObject> paramsList)
{
  if (paramsList != null)
  {
     return "recieved a list with length:" + paramsList.Count;
  }

  return "NOTHING RECIEVED...";
}

Calling with Json:

User-Agent: Fiddler
Content-Type: application/json
Host: localhost:49407
Content-Length: 91

[{"Id1":3,"Id2":76,"Id3":19},{"Id1":56,"Id2":87,"Id3":94},{"Id1":976,"Id2":345,"Id3":7554}]

WebApiParams_05_json

Calling with XML:

User-Agent: Fiddler
Content-Type: application/xml
Host: localhost:49407
Content-Length: 258

<ArrayOfParamsObject>
<ParamsObject><Id1>3</Id1><Id2>76</Id2><Id3>19</Id3></ParamsObject>
<ParamsObject><Id1>56</Id1><Id2>87</Id2><Id3>94</Id3></ParamsObject>
<ParamsObject><Id1>976</Id1><Id2>345</Id2><Id3>7554</Id3></ParamsObject>
</ArrayOfParamsObject>

WebApiParams_04_xml

Example 8: Sending object lists in the Body

[Route("example8")]
[HttpPost]
public string GetListsFromBody([FromBody] List<List<ParamsObject>> paramsList)
{
  if (paramsList != null)
  {
	return "recieved a list with length:" + paramsList.Count;
  }

  return "NOTHING RECIEVED...";
}

This is a little bit different to the previous examples. The body can only send one single object to Web API. Because of this, the lists of objects are wrapped in a list or a parent object.

POST http://localhost:49407/api/values/example8 HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:49407
Content-Length: 185

[
 [
  {"Id1":3,"Id2":76,"Id3":19},
  {"Id1":56,"Id2":87,"Id3":94},
  {"Id1":976,"Id2":345,"Id3":7554}
 ],
 [
  {"Id1":3,"Id2":76,"Id3":19},
  {"Id1":56,"Id2":87,"Id3":94},
  {"Id1":976,"Id2":345,"Id3":7554}
 ]
]

Customizing the parameters

What if the default parameter binding is not enough? Then you can use the ModelBinder class to change your parameters and create your own parameter formats. You could also use ActionFilters for this. Many blogs exist which already explains how to use the ModelBinder class. See the links underneath.

Files and binaries

Files or binaries can also be sent to Web API methods. The article demonstrates how to do this.

Links:

http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/CustomParameterBinding/

http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/

http://www.roelvanlisdonk.nl/?p=3505

http://stackoverflow.com/questions/9981330/how-to-pass-an-array-of-integers-to-a-asp-net-web-api-rest-service

http://stackoverflow.com/questions/14628576/passing-an-json-array-to-mvc-web-api-via-get

18 comments

  1. Thanks man

  2. Really good

  3. Duncan Wilson · · Reply

    Thank you Damian.
    I know this in a old post, but can one implement a string parameter that allow an ampersand
    // http://localhost:49407/api/values/example10/Smith&Son
    // http://localhost:49407/api/values/example10/Smith%26Son
    [Route(“example10/{id1})]
    [HttpGet]
    public string GetWithStringParametersAttributeRouting(string s)
    {
    return s;
    }

    Any call from fiddler or IE will raise “A potentially dangerous Request.Path value was detected from the client (&).”

    1. HI Duncan

      Not that I know of, but you could add the parameter to the body of the request or use base64 encoding

      Greetings Damien

  4. Thanks. I’ve been trying to get this FromBody binding to work.

  5. mAhnaz · · Reply

    Really good.
    thanks alot

  6. […] [Originally Posted By]: https://damienbod.com/2014/08/22/web-api-2-exploring-parameter-binding/ […]

  7. This is driving me nuts. Any time I pass an object to the body, it comes in null. I’m using odata 4 with webapi and if find the guy who wrote this stuff…

    1. Hi Rico, post you code on github or stackoverflow or an example like your code , the examples on asp.net should work.

      http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api

      Greetings Damien

  8. Ramana · · Reply

    Really good, very helpful for me and save my day

  9. Tung Nguyen · · Reply

    Awesome post. simple and easy to understand

  10. srivindhya · · Reply

    hi,
    I downloaded the code sample from ” https://github.com/damienbod/WebApiParameters“.
    I tried Run the project, but Example 6: Sending a simple list in the Url is not able to send the List data using Get Method.Can we send the list data using URL.
    Explain me.
    Thanks

  11. […] Web API 2 Exploring Parameter Binding […]

  12. Rafael Brizuela · · Reply

    thanks very much. I was looking for the ways of mapping request param in xml format to object within my API. When I updated the Global.asax file as you suggested then it worked fine. Now I have a question. What if the xml nodes come with attributes, how those attributes are getting mapped to the object elements?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.