Pau*_*ver 11 c# asp.net-mvc asp.net-mvc-4 asp.net-web-api
我想验证Web API REST命令的输入.我希望它能够像State
下面那样使用限制参数有效值的属性进行修饰.
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; }
...
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在不违背Web API的情况下做到这一点.理想情况下,该方法类似于Ruby on Rails的自定义验证.
Mat*_*ser 25
创建从中派生ValidationAttribute
并覆盖IsValid
成员函数的自定义验证属性.
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
那你可以做
[ValidValues("New", "Used", "Unknown")]
Run Code Online (Sandbox Code Playgroud)
上述代码尚未编译或测试.
归档时间: |
|
查看次数: |
11909 次 |
最近记录: |