Skip to content

Instantly share code, notes, and snippets.

@lencharest
Created January 6, 2016 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lencharest/b8194a014a11e09cdba6 to your computer and use it in GitHub Desktop.
Save lencharest/b8194a014a11e09cdba6 to your computer and use it in GitHub Desktop.
Web API Model Binder for Route Data
using System;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
namespace Example
{
public class RouteDataModelBinder : IModelBinder
{
#region IModelBinder Members
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
object model;
if (!actionContext.RequestContext.RouteData.Values.TryGetValue(bindingContext.ModelName, out model))
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, $"No route data named '{bindingContext.ModelName}'.");
return false;
}
if (!bindingContext.ModelType.IsAssignableFrom(model.GetType()))
{
try
{
model = Convert.ChangeType(model, bindingContext.ModelType);
}
catch
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, $"Route data cannot be converted to type '{bindingContext.ModelType.FullName}'.");
return false;
}
}
bindingContext.Model = model;
return true;
}
#endregion
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public class RouteDataAttribute : ModelBinderAttribute
{
public RouteDataAttribute()
{
this.BinderType = typeof(RouteDataModelBinder);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment