Asp.Net Web API中用于十进制的自定义模型绑定器

Fel*_*ani 4 c# asp.net rest asp.net-mvc asp.net-web-api

我有一个使用asp.net mvc web api的web api应用程序,它在viewmodels中收到一些十进制数字.我想为decimal类型创建一个自定义模型绑定器,并使其适用于所有小数数字.我有一个像这样的viewModel:

public class ViewModel
{
   public decimal Factor { get; set; }
   // other properties
}
Run Code Online (Sandbox Code Playgroud)

并且前端应用程序可以发送带有无效十进制数的json,如: 457945789654987654897654987.79746579651326549876541326879854

我想回复一个400 - Bad Request错误和自定义消息.我尝试创建一个自定义模型绑定器System.Web.Http.ModelBinding.IModelBinder,在global.asax上实现和registring,但不起作用.我想让它在我的代码中使用所有小数,看看我尝试了什么:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

添加Application_Start:

GlobalConfiguration.Configuration.BindParameter(typeof(decimal), new DecimalValidatorModelBinder());
Run Code Online (Sandbox Code Playgroud)

我能做什么?谢谢.

Mik*_*son 5

默认情况下,Web API使用媒体类型格式化程序从请求正文中读取复杂类型.因此,在这种情况下,它不会通过模型绑定器.