WebAPI拒绝无效的枚举值

WebAPI拒绝无效的枚举值

本文介绍了MVC4 WebAPI拒绝无效的枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使JSON.NET/MVC 4 WebAPI拒绝枚举没有成员的整数值?例如:

How can I make JSON.NET / MVC 4 WebAPI reject integer values for which the enum has no member? Eg:

如果我有这个模型:

public enum Colour { Red = 1 };

public class Model
{
  public Colour Colour { get; set; }
}

Model Post(Model model)
{
   // model.Colour could be 99, 34234234, 0 etc, etc
}

如果我发布{ Color: 9999 },则最终得到一个模型,其中model.Color = 999,我想返回一个Bad Request状态代码.

If I post { Color: 9999 }, I end up with a model where model.Color = 999 and I want to return a Bad Request status code instead.

推荐答案

一种选择是编写验证器:

One option is to write a validator:

public class ValidEnumValueAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        Type enumType = value.GetType();
        bool valid = Enum.IsDefined(enumType, value);
        if (!valid)
        {
            return new ValidationResult(String.Format("{0} is not a valid value for type {1}", value, enumType.Name));
        }
        return ValidationResult.Success;
    }
}

用作:

public enum Color {Red = 1, Blue = 2}

public class Car
{
    [ValidEnumValue]
    public Color Color { get; set; }
}

在控制器中,ModelState.IsValid将为false.
如果您确实想使请求失败,也可以抛出ValidationException,但是我不确定是否应该使用它们.

In the controller, ModelState.IsValid would be false.
You can also throw a ValidationException, if you really want to fail the request, but I'm not quite sure that is how they should be used.

这篇关于MVC4 WebAPI拒绝无效的枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:08