Web API provides some great out of box experience with parameter binding. It also provides some powerful extensibility points to allow you customize that binding process. For example, you can bind multiple parameters from uri. However, it can only bind one parameter from request content by default. If you try to mark multiple parameters with [FromBody] attribute, you will get an error. The other good example is sometimes people might want to bind a parameter from some other source instead of request. There are also occasions where some parameter might come from either request uri or request body. For all those situations, a custom parameter binding will be your friend.
Say you have a controller that will take an IPrincipal as an parameter. The IPrincipal is not coming from request. So your action looks like the following.
Here is your custom parameter binding to bind a custom principal to the IPrincipal parameter.
Sometimes, server might need to handle different type of requests. Some requests have information stored in the request Uri, and others have them stored in the request body. Here is how you can write one action to handle both types of requests. Your action code might look like the following:
Your custom parameter binding can delegate the work to either FromUri or FromBody.
Due to various reasons, the request sometimes contains a different name for a property than the actual property name defined on the server. How do we get those mapped correctly? For example, here is the type definition that its property is named "Name" on the server, but the client wants to send it using "$Name" instead.
Here is how the action could look like.
This might be the most common case where you want to use custom parameter bindings. Out of box, one could only bind one parameter from request body. It forces user who want to bind multiple objects having to write a wrapper class to wrap all those parameters. Fortunately, you can also write a custom parameter binding to solve that problem elegantly. Here is how your action might look like, and your first name and last name are coming from request body.
Now let us write a parameter binding to map those values from request body to firstname and lastname parameters.
Now we have all those wonderful custom Parameter Bindings, how do you tell Web API that you want to use them instead of those default ones? Here is how you can do it.
To summarize, custom parameter binding is a powerful extensibility point which allows users to take full control of the parameter binding process. To learn more details, you can download the sample code from our aspnet codeplex site at http://aspnet.codeplex.com/SourceControl/changeset/66590b705e5b.
Happy coding with ASPNET Web API!