【问题标题】:Handling decimal parameters in webapi在 webapi 中处理十进制参数
【发布时间】:2016-12-20 09:33:47
【问题描述】:
/api/WebService?param1=1&price=6.2 工作
/api/WebService?param1=1&price=6,2 不工作。请求无效错误。

根据逗号设置服务器区域设置,我将全球化“tr-TR”放在 webconfig 上,但它不适用于逗号。此外,我尝试过 ModelBinder,但它也不起作用。

如何使它与逗号一起使用?

【问题讨论】:

  • 您必须将价格参数设为字符串类型。可能是现在使用小数
  • 是的,这是解决方案之一,但不幸的是不是我想要的。

标签: asp.net-mvc asp.net-web-api decimal model-binding globalization


【解决方案1】:

像这样使用模型绑定器:

 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());
}

发现于:ASP.NET MVC datetime culture issue when passing value back to controller

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2018-05-11
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多