Binding Parameter Types in Web API (or how to pass a string array...

by Michael Szul on

No ads, no tracking, and no data collection. Enjoy this article? Buy us a ☕.

ASP.NET Web API does a fantastic job at parameter binding, and offers a powerful, transparent way for data on the frontend to be bound to models on the backend. When you generate a controller scaffold from a model, you get the basic CRUD operations, but you'll also notice that both POST (create/insert) and PUT (update) controller methods accept parameter objects of the model type. The Web API serializes and deserializes these items behind the scenes.

This behind the scenes magic is great, but it can also confuse new programmers when they attempt to pass information that isn't bound to the model type. Parameters for strings and integers works as expected, but what about something like a string array?

The following will not work:

public IEnumerable<YOUR_MODEL> GetSearch(string[] terms)
      {
      ...
      }
      

What's going on in this code snippet? Imagine a scenario where you need to search a particular model's data set, but with the potential for multiple search terms. For example, the query string in HTTP allows for multiple parameters of the same name, so what if you needed to send this collection of search terms to the backend? The above code will not result in a useable API URL.

Instead, you have to use the FromUri attribute to get the Web API to bind the parameters appropriately:

public IEnumerable<YOUR_MODEL> GetSearch([FromUri] string[] terms)
      {
      ...
      }
      

FromUri is the Web API way of binding data from the frontend to method parameters on the backend. Use of FromUri and FromBody(for post parameters) was a little more explicitly used and discussed in Web API 1.0, but less so in Web API 2.0.