Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c# - Web API custom validation to check string against list of approved values

I'd like to validate an input on a Web API REST command. I'd like it to work something like State below being decorated with an attribute that limits the valid values for the parameter.

public class Item {
    ...

    // I want State to only be one of "New", "Used", or "Unknown"
    [Required]
    [ValidValues({"New", "Used", "Unknown"})]
    public string State { get; set; }

    [Required]
    public string Description { get; set; }

    ...
}

Is there a way to do this without going against the grain of Web API. Ideally the approach would be similar to Ruby on Rails' custom validation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a custom validation attribute derived from ValidationAttribute and override the IsValid member function.

public class ValidValuesAttribute: ValidationAttribute
{
  string[] _args;

  public ValidValuesAttribute(params string[] args)
  {
    _args = args;
  }

  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  {
    if (_args.Contains((string)value))
      return ValidationResult.Success;
    return new ValidationResult("Invalid value.");
  }
}

Then you can do

[ValidValues("New", "Used", "Unknown")]

The above code has not been compiled or tested.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...