本文介绍了网页API定制验证检查字符串核定值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想验证的Web API REST命令的输入。我想它的工作有点像国家
下面正在装修与该参数限制了有效的值的属性。
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; }
...
}
有没有办法做到这一点没有去针对Web API的粮食。理想情况下,方法是类似于Ruby on Rails的自定义验证。
推荐答案
创建 ValidationAttribute
导出自定义验证属性,并覆盖的IsValid
成员函数。
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.");
}
}
然后,你可以做
[ValidValues("New", "Used", "Unknown")]
的上面code尚未编译或测试。的
这篇关于网页API定制验证检查字符串核定值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!