How to customize parameter binding
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.
Scenario 1: How to bind a parameter not coming from request
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.
Code Snippet
- [HttpGet]
- public HttpResponseMessage BindPrincipal(IPrincipal principal)
- {
- return Request.CreateResponse(System.Net.HttpStatusCode.Accepted,
- String.Format("BindPrincipal with Principal name {0}.", principal.Identity.Name));
- }
Here is your custom parameter binding to bind a custom principal to the IPrincipal parameter.
Code Snippet
- /// <summary>
- /// A Custom HttpParameterBinding to bind a complex type, e.g. IPrincipal, which is not coming from request
- /// </summary>
- public class PrincipalParameterBinding : HttpParameterBinding
- {
- public PrincipalParameterBinding(HttpParameterDescriptor desc)
- : base(desc)
- {
- }
- public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
- {
- // Set the binding result here
- SetValue(actionContext, new GenericPrincipal(new GenericIdentity("MyIdentity"), new string[]{"myrole"}));
- // now, we can return a completed task with no result
- TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
- tcs.SetResult(default(AsyncVoid));
- return tcs.Task;
- }
- private struct AsyncVoid
- {
- }
- }
Scenario 2: How to bind a complex type either from body or from uri
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:
Code Snippet
- [HttpGet]
- [HttpPost]
- public HttpResponseMessage BindCustomComplexTypeFromUriOrBody(TestItem item)
- {
- return Request.CreateResponse(System.Net.HttpStatusCode.Accepted,
- String.Format("BindCustomComplexTypeFromUriOrBody returns item.Name = {0}.", item.Name));
- }
Your custom parameter binding can delegate the work to either FromUri or FromBody.
Code Snippet
- /// <summary>
- /// A Custom HttpParameterBinding to bind a complex type either from request body or uri
- /// </summary>
- public class FromUriOrBodyParameterBinding : HttpParameterBinding
- {
- HttpParameterBinding _defaultUriBinding;
- HttpParameterBinding _defaultFormatterBinding;
- public FromUriOrBodyParameterBinding(HttpParameterDescriptor desc)
- : base(desc)
- {
- _defaultUriBinding = new FromUriAttribute().GetBinding(desc);
- _defaultFormatterBinding = new FromBodyAttribute().GetBinding(desc);
- }
- public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
- {
- if (actionContext.Request.Content != null && actionContext.Request.Content.Headers.ContentLength > 0)
- {
- // we have something from the body, try that first
- return _defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
- }
- else
- {
- // we need to read things from uri
- return _defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
- }
- }
- }
Scenario 3: How to bind a parameter with a different property Name
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.
Code Snippet
- public class TestItemRenameProperty
- {
- [DataMember(Name = "$Name")]
- public string Name { get; set; }
- }
Here is how the action could look like.
Code Snippet
- [HttpGet]
- public HttpResponseMessage BindCustomComplexTypeFromUriWithRenamedProperty(TestItemRenameProperty item)
- {
- return Request.CreateResponse(System.Net.HttpStatusCode.Accepted,
- String.Format("BindCustomComplexTypeFromUriWithRenamedProperty item.Name = {0}.", item.Name));
- }
Scenario 4: How to bind multiple parameters form a request body
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.
Code Snippet
- [HttpPost]
- public HttpResponseMessage PostMultipleParametersFromBody(string firstname, string lastname)
- {
- return Request.CreateResponse(System.Net.HttpStatusCode.Accepted,
- String.Format("BindCustomCoPostMultipleParametersFromBodymplexType FristName = {0}, LastName = {1}.", firstname, lastname));
- }
Now let us write a parameter binding to map those values from request body to firstname and lastname parameters.
Code Snippet
- /// <summary>
- /// A Custom HttpParameterBinding to bind multiple parameters from request body
- /// </summary>
- public class MultipleParameterFromBodyParameterBinding : HttpParameterBinding
- {
- private const string MultipleBodyParameters = "MultipleBodyParameters";
- public MultipleParameterFromBodyParameterBinding(HttpParameterDescriptor descriptor)
- : base(descriptor)
- {
- }
- public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
- {
- NameValueCollection col = TryReadBody(actionContext.Request);
- if (col == null)
- {
- throw new HttpResponseException(System.Net.HttpStatusCode.BadRequest);
- }
- // Set the binding result here
- SetValue(actionContext, col[Descriptor.ParameterName]);
- // now, we can return a completed task with no result
- TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
- tcs.SetResult(default(AsyncVoid));
- return tcs.Task;
- }
- NameValueCollection TryReadBody(HttpRequestMessage request)
- {
- object result = null;
- if (!request.Properties.TryGetValue(MultipleBodyParameters, out result))
- {
- // parsing the string like firstname=Hongmei&lastname=Ge
- NameValueCollection collection = new NameValueCollection();
- result = request.Content.ReadAsFormDataAsync().Result;
- request.Properties.Add(MultipleBodyParameters, result);
- }
- return result as NameValueCollection;
- }
- private struct AsyncVoid
- {
- }
- }
Final step: How to register a custom parameter binding
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.
Code Snippet
- // Register an action to create custom ParameterBinding
- config.ParameterBindingRules.Insert(0, GetCustomParameterBinding);
Code Snippet
- public static HttpParameterBinding GetCustomParameterBinding(HttpParameterDescriptor descriptor)
- {
- if (descriptor.ParameterType == typeof(IPrincipal))
- {
- return new PrincipalParameterBinding(descriptor);
- }
- else if ( descriptor.ParameterType == typeof(TestItem))
- {
- return new FromUriOrBodyParameterBinding(descriptor);
- }
- else if (descriptor.ParameterType == typeof(TestItemRenameProperty))
- {
- return new CustomModelBinderWithPropertyName(descriptor);
- }
- else if ( descriptor.ParameterType == typeof(string) )
- {
- return new MultipleParameterFromBodyParameterBinding(descriptor);
- }
- // any other types, let the default parameter binding handle
- return null;
- }
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 https://aspnet.codeplex.com/SourceControl/changeset/66590b705e5b.
Happy coding with ASPNET Web API!
Comments
Anonymous
April 09, 2013
"Scenario 3: How to bind a parameter with a different property Name" doesn't work!Anonymous
August 04, 2015
Thanks great post just what I needed and the only one I could find on how to implement your own binding using HttpParameterBinding. Your PrincipalParameterBinding example can now be simplified to return Task.FromResult(0);