我有一个使用asp.net mvc web api的web api应用程序,它在viewmodels中收到一些十进制数字。我想为decimal
类型创建一个自定义模型绑定器,并使其适用于所有小数数字。我有一个像这样的viewModel:
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());
我该怎么办? 谢谢。
答案 0 :(得分:5)
默认情况下,Web API使用媒体类型格式化程序从请求正文中读取复杂类型。因此,在这种情况下,它不会通过模型绑定器。
答案 1 :(得分:0)
对于JSON,您可以创建JsonConverter(如果您默认使用JSON.NET:
public class DoubleConverter : JsonConverter
{
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(double) || objectType == typeof(double?));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
{
return token.ToObject<double>();
}
if (token.Type == JTokenType.String)
{
// customize this to suit your needs
var wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
var alternateSeparator = wantedSeperator == "," ? "." : ",";
double actualValue;
if (double.TryParse(token.ToString().Replace(alternateSeparator, wantedSeperator), NumberStyles.Any,
CultureInfo.CurrentCulture, out actualValue))
{
return actualValue;
}
else
{
throw new JsonSerializationException("Unexpected token value: " + token.ToString());
}
}
if (token.Type == JTokenType.Null && objectType == typeof(double?))
{
return null;
}
if (token.Type == JTokenType.Boolean)
{
return token.ToObject<bool>() ? 1 : 0;
}
throw new JsonSerializationException("Unexpected token type: " + token.Type.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
}
}