Web Api 2十进制分隔符

时间:2016-07-08 07:17:11

标签: c# asp.net asp.net-web-api asp.net-web-api2

如何为十进制数创建模型绑定器,如果用户以错误的格式发送它会引发异常?

我需要这样的东西:

2 = OK
2.123 = OK
2,123 = throw invalid format exception

1 个答案:

答案 0 :(得分:1)

请看这篇文章http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

您可以像这样使用标准活页夹进行简单检查

public class DecimalModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;

        if (valueResult.AttemptedValue.Contains(","))
        {
            throw new Exception("Some exception");
        }
        actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
            CultureInfo.CurrentCulture);


        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        bindingContext.Model = actualValue;
        return true;
    }
}

编辑:根据@Liam建议,您必须先将此活页夹添加到您的配置

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());

上面的代码在错误的小数分隔符的情况下抛出异常,但您应该使用模型验证来检测那种错误。它更灵活。

public class DecimalModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            if (valueResult.AttemptedValue.Contains(","))
            {
                throw new Exception("Some exception");
            }
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
            return false;
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        bindingContext.Model = actualValue;
        return true;
    }
}

您不会抛出异常但只是添加验证错误。您可以稍后在控制器中查看

if (ModelState.IsValid)
{
}