Created
January 6, 2016 18:10
-
-
Save lencharest/b8194a014a11e09cdba6 to your computer and use it in GitHub Desktop.
Web API Model Binder for Route Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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