【发布时间】:2013-07-31 02:10:27
【问题描述】:
我有一个使用 asp.net mvc web api 的 web api 应用程序,它在视图模型中接收一些十进制数字。我想为decimal 类型创建一个自定义模型绑定器,并让它适用于所有小数。我有一个这样的视图模型:
public class ViewModel
{
public decimal Factor { get; set; }
// other properties
}
前端应用程序可以发送带有无效十进制数的 json,例如:457945789654987654897654987.79746579651326549876541326879854
我想回复 400 - Bad Request 错误和自定义消息。我尝试创建一个自定义模型绑定器,实现System.Web.Http.ModelBinding.IModelBinder 并在 global.asax 上注册,但不起作用。我想让它适用于我的代码中的所有小数,看看我尝试了什么:
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))] 的参数之前
-
它会验证我的十进制属性还是我在 post 方法上的整个对象?我只想在所有帖子中验证我的小数属性。
-
也许这可以解决你的问题stackoverflow.com/questions/9434848/…
-
究竟是什么不起作用?模型绑定器是否从未被调用,ValueProvider 不返回值还是只是没有值绑定到方法参数?
-
我一般使用
System.Web.Mvc中的IModelBinder,而不是System.Web.Http.ModelBinding,然后在我的Global.asax文件中使用如下代码:ModelBinders.Binders.Add(typeof(decimal), new DecimalValidatorModelBinder());
标签: c# asp.net asp.net-mvc rest asp.net-web-api