Handling decimal parameters in webapi

1k views Asked by At
/api/WebService?param1=1&price=6.2 working
/api/WebService?param1=1&price=6,2 not working. The request is invalid error.

Server region settings set according to comma and i put globalization "tr-TR" on webconfig yet it does not work with comma. Besides i have tried ModelBinder however it does not work either.

How can i make it work with comma?

1

There are 1 answers

0
ArDumez On

Use model binder like this:

 public class DecimalModelBinder : IModelBinder
 {
   public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
     ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
     ModelState modelState = new ModelState { Value = valueResult };
     object actualValue = null;
     try
     {
       actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
     }
     catch (FormatException e)
     {
       modelState.Errors.Add(e);
     }

     bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
     return actualValue;
  }
}


protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);

  //HERE you tell the framework how to handle decimal values
  ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());

  DependencyResolver.SetResolver(new ETAutofacDependencyResolver());
}

Found in : ASP.NET MVC datetime culture issue when passing value back to controller