I have a web api application using asp.net mvc web api that get some decimal numbers in viewmodels models. I would like to create a custom mediator for the decimal type and make it work for all decimal numbers. I have a viewModel like this:
public class ViewModel { public decimal Factor { get; set; }
And the external application can send json with an invalid decimal number, for example: 457945789654987654897654987.79746579651326549876541326879854
I would like to respond with a 400 - Bad Request error and a custom message. I tried to create a custom mediator that implements System.Web.Http.ModelBinding.IModelBinder and register on global.asax, but it does not work. I would like to make it work for all decimal places in my code, see 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;
Adding on Application_Start :
GlobalConfiguration.Configuration.BindParameter(typeof(decimal), new DecimalValidatorModelBinder());
What can I do? Thanks.
source share