"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Parameter Binding in ASP.NET Web API

by Mike Wasson

When Web API calls a method on a controller, it must set values for the parameters, a process called binding. This article describes how Web API binds parameters, and how you can customize the binding process.

By default, Web API uses the following rules to bind parameters:

For example, here is a typical Web API controller method:

[!code-csharpMain]

   1:  HttpResponseMessage Put(int id, Product item) { ... }

The id parameter is a “simple” type, so Web API tries to get the value from the request URI. The item parameter is a complex type, so Web API uses a media-type formatter to read the value from the request body.

To get a value from the URI, Web API looks in the route data and the URI query string. The route data is populated when the routing system parses the URI and matches it to a route. For more information, see Routing and Action Selection.

In the rest of this article, I’ll show how you can customize the model binding process. For complex types, however, consider using media-type formatters whenever possible. A key principle of HTTP is that resources are sent in the message body, using content negotiation to specify the representation of the resource. Media-type formatters were designed for exactly this purpose.

Using [FromUri]

To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.

[!code-csharpMain]

   1:  public class GeoPoint
   2:  {
   3:      public double Latitude { get; set; } 
   4:      public double Longitude { get; set; }
   5:  }
   6:   
   7:  public ValuesController : ApiController
   8:  {
   9:      public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
  10:  }

The client can put the Latitude and Longitude values in the query string and Web API will use them to construct a GeoPoint. For example:

http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

[!code-csharpMain]

   1:  public HttpResponseMessage Post([FromBody] string name) { ... }

In this example, Web API will use a media-type formatter to read the value of name from the request body. Here is an example client request.

[!code-consoleMain]

   1:  POST http://localhost:5076/api/values HTTP/1.1
   2:  User-Agent: Fiddler
   3:  Host: localhost:5076
   4:  Content-Type: application/json
   5:  Content-Length: 7
   6:  "Alice"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is “application/json” and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body. So this will not work:

[!code-csharpMain]

   1:  // Caution: Will not work!    
   2:  public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Type Converters

You can make Web API treat a class as a simple type (so that Web API will try to bind it from the URI) by creating a TypeConverter and providing a string conversion.

The following code shows a GeoPoint class that represents a geographical point, plus a TypeConverter that converts from strings to GeoPoint instances. The GeoPoint class is decorated with a [TypeConverter] attribute to specify the type converter. (This example was inspired by Mike Stall’s blog post How to bind to custom objects in action signatures in MVC/WebAPI.)

[!code-csharpMain]

   1:  [TypeConverter(typeof(GeoPointConverter))]
   2:  public class GeoPoint
   3:  {
   4:      public double Latitude { get; set; } 
   5:      public double Longitude { get; set; }
   6:   
   7:      public static bool TryParse(string s, out GeoPoint result)
   8:      {
   9:          result = null;
  10:   
  11:          var parts = s.Split(',');
  12:          if (parts.Length != 2)
  13:          {
  14:              return false;
  15:          }
  16:   
  17:          double latitude, longitude;
  18:          if (double.TryParse(parts[0], out latitude) &&
  19:              double.TryParse(parts[1], out longitude))
  20:          {
  21:              result = new GeoPoint() { Longitude = longitude, Latitude = latitude };
  22:              return true;
  23:          }
  24:          return false;
  25:      }
  26:  }
  27:   
  28:  class GeoPointConverter : TypeConverter
  29:  {
  30:      public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  31:      {
  32:          if (sourceType == typeof(string))
  33:          {
  34:              return true;
  35:          }
  36:          return base.CanConvertFrom(context, sourceType);
  37:      }
  38:   
  39:      public override object ConvertFrom(ITypeDescriptorContext context, 
  40:          CultureInfo culture, object value)
  41:      {
  42:          if (value is string)
  43:          {
  44:              GeoPoint point;
  45:              if (GeoPoint.TryParse((string)value, out point))
  46:              {
  47:                  return point;
  48:              }
  49:          }
  50:          return base.ConvertFrom(context, culture, value);
  51:      }
  52:  }

Now Web API will treat GeoPoint as a simple type, meaning it will try to bind GeoPoint parameters from the URI. You don’t need to include [FromUri] on the parameter.

[!code-csharpMain]

   1:  public HttpResponseMessage Get(GeoPoint location) { ... }

The client can invoke the method with a URI like this:

http://localhost/api/values/?location=47.678558,-122.130989

Model Binders

A more flexible option than a type converter is to create a custom model binder. With a model binder, you have access to things like the HTTP request, the action description, and the raw values from the route data.

To create a model binder, implement the IModelBinder interface. This interface defines a single method, BindModel:

[!code-csharpMain]

   1:  bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);

Here is a model binder for GeoPoint objects.

[!code-csharpMain]

   1:  public class GeoPointModelBinder : IModelBinder
   2:  {
   3:      // List of known locations.
   4:      private static ConcurrentDictionary<string, GeoPoint> _locations
   5:          = new ConcurrentDictionary<string, GeoPoint>(StringComparer.OrdinalIgnoreCase);
   6:   
   7:      static GeoPointModelBinder()
   8:      {
   9:          _locations["redmond"] = new GeoPoint() { Latitude = 47.67856, Longitude = -122.131 };
  10:          _locations["paris"] = new GeoPoint() { Latitude = 48.856930, Longitude = 2.3412 };
  11:          _locations["tokyo"] = new GeoPoint() { Latitude = 35.683208, Longitude = 139.80894 };
  12:      }
  13:   
  14:      public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
  15:      {
  16:          if (bindingContext.ModelType != typeof(GeoPoint))
  17:          {
  18:              return false;
  19:          }
  20:   
  21:          ValueProviderResult val = bindingContext.ValueProvider.GetValue(
  22:              bindingContext.ModelName);
  23:          if (val == null)
  24:          {
  25:              return false;
  26:          }
  27:   
  28:          string key = val.RawValue as string;
  29:          if (key == null)
  30:          {
  31:              bindingContext.ModelState.AddModelError(
  32:                  bindingContext.ModelName, "Wrong value type");
  33:              return false;
  34:          }
  35:   
  36:          GeoPoint result;
  37:          if (_locations.TryGetValue(key, out result) || GeoPoint.TryParse(key, out result))
  38:          {
  39:              bindingContext.Model = result;
  40:              return true;
  41:          }
  42:   
  43:          bindingContext.ModelState.AddModelError(
  44:              bindingContext.ModelName, "Cannot convert value to Location");
  45:          return false;
  46:      }
  47:  }

A model binder gets raw input values from a value provider. This design separates two distinct functions:

The default value provider in Web API gets values from the route data and the query string. For example, if the URI is http://localhost/api/values/1?location=48,-122, the value provider creates the following key-value pairs:

(I’m assuming the default route template, which is “api/{controller}/{id}”.)

The name of the parameter to bind is stored in the ModelBindingContext.ModelName property. The model binder looks for a key with this value in the dictionary. If the value exists and can be converted into a GeoPoint, the model binder assigns the bound value to the ModelBindingContext.Model property.

Notice that the model binder is not limited to a simple type conversion. In this example, the model binder first looks in a table of known locations, and if that fails, it uses type conversion.

Setting the Model Binder

There are several ways to set a model binder. First, you can add a [ModelBinder] attribute to the parameter.

[!code-csharpMain]

   1:  public HttpResponseMessage Get([ModelBinder(typeof(GeoPointModelBinder))] GeoPoint location)

You can also add a [ModelBinder] attribute to the type. Web API will use the specified model binder for all parameters of that type.

[!code-csharpMain]

   1:  [ModelBinder(typeof(GeoPointModelBinder))]
   2:  public class GeoPoint
   3:  {
   4:      // ....
   5:  }

Finally, you can add a model-binder provider to the HttpConfiguration. A model-binder provider is simply a factory class that creates a model binder. You can create a provider by deriving from the ModelBinderProvider class. However, if your model binder handles a single type, it’s easier to use the built-in SimpleModelBinderProvider, which is designed for this purpose. The following code shows how to do this.

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          var provider = new SimpleModelBinderProvider(
   6:              typeof(GeoPoint), new GeoPointModelBinder());
   7:          config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
   8:   
   9:          // ...
  10:      }
  11:  }

With a model-binding provider, you still need to add the [ModelBinder] attribute to the parameter, to tell Web API that it should use a model binder and not a media-type formatter. But now you don’t need to specify the type of model binder in the attribute:

[!code-csharpMain]

   1:  public HttpResponseMessage Get([ModelBinder] GeoPoint location) { ... }

Value Providers

I mentioned that a model binder gets values from a value provider. To write a custom value provider, implement the IValueProvider interface. Here is an example that pulls values from the cookies in the request:

[!code-csharpMain]

   1:  public class CookieValueProvider : IValueProvider
   2:  {
   3:      private Dictionary<string, string> _values;
   4:   
   5:      public CookieValueProvider(HttpActionContext actionContext)
   6:      {
   7:          if (actionContext == null)
   8:          {
   9:              throw new ArgumentNullException("actionContext");
  10:          }
  11:   
  12:          _values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  13:          foreach (var cookie in actionContext.Request.Headers.GetCookies())
  14:          {
  15:              foreach (CookieState state in cookie.Cookies)
  16:              {
  17:                  _values[state.Name] = state.Value;
  18:              }
  19:          }
  20:      }
  21:   
  22:      public bool ContainsPrefix(string prefix)
  23:      {
  24:          return _values.Keys.Contains(prefix);
  25:      }
  26:   
  27:      public ValueProviderResult GetValue(string key)
  28:      {
  29:          string value;
  30:          if (_values.TryGetValue(key, out value))
  31:          {
  32:              return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
  33:          }
  34:          return null;
  35:      }
  36:  }

You also need to create a value provider factory by deriving from the ValueProviderFactory class.

[!code-csharpMain]

   1:  public class CookieValueProviderFactory : ValueProviderFactory
   2:  {
   3:      public override IValueProvider GetValueProvider(HttpActionContext actionContext)
   4:      {
   5:          return new CookieValueProvider(actionContext);
   6:      }
   7:  }

Add the value provider factory to the HttpConfiguration as follows.

[!code-csharpMain]

   1:  public static void Register(HttpConfiguration config)
   2:  {
   3:      config.Services.Add(typeof(ValueProviderFactory), new CookieValueProviderFactory());
   4:   
   5:      // ...
   6:  }

Web API composes all of the value providers, so when a model binder calls ValueProvider.GetValue, the model binder receives the value from the first value provider that is able to produce it.

Alternatively, you can set the value provider factory at the parameter level by using the ValueProvider attribute, as follows:

[!code-csharpMain]

   1:  public HttpResponseMessage Get(
   2:      [ValueProvider(typeof(CookieValueProviderFactory))] GeoPoint location)

This tells Web API to use model binding with the specified value provider factory, and not to use any of the other registered value providers.

HttpParameterBinding

Model binders are a specific instance of a more general mechanism. If you look at the [ModelBinder] attribute, you will see that it derives from the abstract ParameterBindingAttribute class. This class defines a single method, GetBinding, which returns an HttpParameterBinding object:

[!code-csharpMain]

   1:  public abstract class ParameterBindingAttribute : Attribute
   2:  {
   3:      public abstract HttpParameterBinding GetBinding(HttpParameterDescriptor parameter);
   4:  }

An HttpParameterBinding is responsible for binding a parameter to a value. In the case of [ModelBinder], the attribute returns an HttpParameterBinding implementation that uses an IModelBinder to perform the actual binding. You can also implement your own HttpParameterBinding.

For example, suppose you want to get ETags from if-match and if-none-match headers in the request. We’ll start by defining a class to represent ETags.

[!code-csharpMain]

   1:  public class ETag
   2:  {
   3:      public string Tag { get; set; }
   4:  }

We’ll also define an enumeration to indicate whether to get the ETag from the if-match header or the if-none-match header.

[!code-csharpMain]

   1:  public enum ETagMatch
   2:  {
   3:      IfMatch,
   4:      IfNoneMatch
   5:  }

Here is an HttpParameterBinding that gets the ETag from the desired header and binds it to a parameter of type ETag:

[!code-csharpMain]

   1:  public class ETagParameterBinding : HttpParameterBinding
   2:  {
   3:      ETagMatch _match;
   4:   
   5:      public ETagParameterBinding(HttpParameterDescriptor parameter, ETagMatch match) 
   6:          : base(parameter)
   7:      {
   8:          _match = match;
   9:      }
  10:   
  11:      public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, 
  12:          HttpActionContext actionContext, CancellationToken cancellationToken)
  13:      {
  14:          EntityTagHeaderValue etagHeader = null;
  15:          switch (_match)
  16:          {
  17:              case ETagMatch.IfNoneMatch:
  18:                  etagHeader = actionContext.Request.Headers.IfNoneMatch.FirstOrDefault();
  19:                  break;
  20:   
  21:              case ETagMatch.IfMatch:
  22:                  etagHeader = actionContext.Request.Headers.IfMatch.FirstOrDefault();
  23:                  break;
  24:          }
  25:   
  26:          ETag etag = null;
  27:          if (etagHeader != null)
  28:          {
  29:              etag = new ETag { Tag = etagHeader.Tag };
  30:          }
  31:          actionContext.ActionArguments[Descriptor.ParameterName] = etag;
  32:   
  33:          var tsc = new TaskCompletionSource<object>();
  34:          tsc.SetResult(null);
  35:          return tsc.Task;
  36:      }
  37:  }

The ExecuteBindingAsync method does the binding. Within this method, add the bound parameter value to the ActionArgument dictionary in the HttpActionContext.

[!NOTE] If your ExecuteBindingAsync method reads the body of the request message, override the WillReadBody property to return true. The request body might be an unbuffered stream that can only be read once, so Web API enforces a rule that at most one binding can read the message body.

To apply a custom HttpParameterBinding, you can define an attribute that derives from ParameterBindingAttribute. For ETagParameterBinding, we’ll define two attributes, one for if-match headers and one for if-none-match headers. Both derive from an abstract base class.

[!code-csharpMain]

   1:  public abstract class ETagMatchAttribute : ParameterBindingAttribute
   2:  {
   3:      private ETagMatch _match;
   4:   
   5:      public ETagMatchAttribute(ETagMatch match)
   6:      {
   7:          _match = match;
   8:      }
   9:   
  10:      public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
  11:      {
  12:          if (parameter.ParameterType == typeof(ETag))
  13:          {
  14:              return new ETagParameterBinding(parameter, _match);
  15:          }
  16:          return parameter.BindAsError("Wrong parameter type");
  17:      }
  18:  }
  19:   
  20:  public class IfMatchAttribute : ETagMatchAttribute
  21:  {
  22:      public IfMatchAttribute()
  23:          : base(ETagMatch.IfMatch)
  24:      {
  25:      }
  26:  }
  27:   
  28:  public class IfNoneMatchAttribute : ETagMatchAttribute
  29:  {
  30:      public IfNoneMatchAttribute()
  31:          : base(ETagMatch.IfNoneMatch)
  32:      {
  33:      }
  34:  }

Here is a controller method that uses the [IfNoneMatch] attribute.

[!code-csharpMain]

   1:  public HttpResponseMessage Get([IfNoneMatch] ETag etag) { ... }

Besides ParameterBindingAttribute, there is another hook for adding a custom HttpParameterBinding. On the HttpConfiguration object, the ParameterBindingRules property is a collection of anomymous functions of type (HttpParameterDescriptor -> HttpParameterBinding). For example, you could add a rule that any ETag parameter on a GET method uses ETagParameterBinding with if-none-match:

[!code-csharpMain]

   1:  config.ParameterBindingRules.Add(p =>
   2:  {
   3:      if (p.ParameterType == typeof(ETag) && 
   4:          p.ActionDescriptor.SupportedHttpMethods.Contains(HttpMethod.Get))
   5:      {
   6:          return new ETagParameterBinding(p, ETagMatch.IfNoneMatch);
   7:      }
   8:      else
   9:      {
  10:          return null;
  11:      }
  12:  });

The function should return null for parameters where the binding is not applicable.

IActionValueBinder

The entire parameter-binding process is controlled by a pluggable service, IActionValueBinder. The default implementation of IActionValueBinder does the following:

  1. Look for a ParameterBindingAttribute on the parameter. This includes [FromBody], [FromUri], and [ModelBinder], or custom attributes.
  2. Otherwise, look in HttpConfiguration.ParameterBindingRules for a function that returns a non-null HttpParameterBinding.
  3. Otherwise, use the default rules that I described previously.

    • If the parameter type is “simple”or has a type converter, bind from the URI. This is equivalent to putting the [FromUri] attribute on the parameter.
    • Otherwise, try to read the parameter from the message body. This is equivalent to putting [FromBody] on the parameter.

If you wanted, you could replace the entire IActionValueBinder service with a custom implementation.

Additional Resources

Custom Parameter Binding Sample

Mike Stall wrote a good series of blog posts about Web API parameter binding:



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api.htm
< THANKS ME>