【问题标题】:Custom Model Binder for Decimal in Asp.Net Web APIAsp.Net Web API 中十进制的自定义模型绑定器
【发布时间】: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


【解决方案1】:

对于 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.");
    }
}

【讨论】:

  • 你在哪里以及如何注册?
【解决方案2】:

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

【讨论】:

  • 我真的在考虑使用 asp.net mvc 作为我的 api 而不是 asp.net web api 哈哈.. 坦克你迈克,这是我没想到会知道的,但这是真的。
  • 你知道我可以为word aorund它提供什么解决方案吗?
  • 不是随便的。媒体类型格式化程序将在任何模型验证发生之前反序列化请求正文......对于 JSON,您可能能够在 JSON.Net 序列化程序上配置一些东西,以更改其默认行为。
猜你喜欢
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
相关资源
最近更新 更多