我有一个使用asp.net mvc web api的web api应用程序,它在viewmodels中接收一些十进制数。我想为decimal
类型创建一个自定义模型联编程序,并让它适用于所有小数数字。我有一个视图模型是这样的:自定义模型绑定器在Asp.Net Web API中的十进制
public class ViewModel
{
public decimal Factor { get; set; }
// other properties
}
而前端应用程序可以发送一个JSON与像一个无效的十进制数:457945789654987654897654987.79746579651326549876541326879854
我想响应与400 - Bad Request
错误和自定义信息。我尝试创建一个自定义模型绑定器,实现global.asax上的System.Web.Http.ModelBinding.IModelBinder
和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);
}
}
添加在Application_Start
:
GlobalConfiguration.Configuration.BindParameter(typeof(decimal), new DecimalValidatorModelBinder());
我能做些什么? 谢谢。
你有没有试图指定的操作参数类型前的粘合剂在操作的参数之前将这个? [ModelBinder(typeof(DecimalValidatorModelBinder))] – Fals
这将验证我的小数属性或我的整个对象上post方法吗?我只是想验证我的小数属性在所有帖子中 –
也许这可以解决您的问题http:// stackoverflow。 com/questions/9434848/custom-model-binder-to-bind-nested-property-values – Fals