Custom Model Binder for Decimal in Asp.Net Web API
asp.net, asp.net-mvc, asp.net-web-api, c#, rest
Solution
By default Web API reads a complex type from the request body using a media-type formatter. So it doesn't go through a model binder in this case.
Problem
I have a web api application using asp.net mvc web api that recieve some decimal numbers in viewmodels. I would like to create a custom model binder for `decimal` type and get it working for all decimals numbers. I have a viewModel like this: ``` public class ViewModel { public decimal Factor { get; set; } // other properties } ``` And the front-end application can send a json with a invalid decimal number like: `457945789654987654897654987.79746579651326549876541326879854` I would like to response with a `400 - Bad Request` error and a custom message. I tried create a custom model binder implementing the `System.Web.Http.ModelBinding.IModelBinder` and registring on the global.asax but does not work. I would like to get it working for all decimals in my code, look what I tried: ``` public class DecimalValidatorModelBinder : System.Web.Http.ModelBinding.IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var input = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (input != null && !string.IsNullOrEmpty(input.AttemptedValue)) { if (bindingContext.ModelType == typeof(decimal)) { decimal result; if (!decimal.TryParse(input.AttemptedValue, NumberStyles.Number, Thread.CurrentThread.CurrentCulture, out result)) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, ErrorHelper.GetInternalErrorList("Invalid decimal number")); return false; } } } return true; //base.BindModel(controllerContext, bindingContext); } } ``` Adding on the `Application_Start`: ``` GlobalConfiguration.Configuration.BindParameter(typeof(decimal), new DecimalValidatorModelBinder()); ``` What can I do? Thank you.