我正在构建一个asp.net webapi2解决方案。作为解决方案的一部分,我通过实现IValidatableObject并返回IEnumerable验证结果来验证请求消息。
示例验证码
public class Request : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (String.IsNullOrEmpty(Customer.FirstName))
yield return new ValidationResult("Customer First Name is mandatory", new[] { "FirstName" });
if (String.IsNullOrEmpty(Customer.LastName))
yield return new ValidationResult("Customer Last Name is mandatory", new[] { "LastName" });
}
}
验证失败时,响应将显示以下内容
<Error>
<Message>The request is invalid.</Message>
<ModelState>
<Request.FirstName>Customer First Name is mandatory</Request.FirstName>
<Request.LastName>Customer Last Name is mandatory</Request.LastName>
</ModelState>
</Error>
是否可以继续使用ValidationResult并按如下所示自定义响应。
<Response>
<Errors>
<Message>Customer First Name is mandatory</Message>
<Message>Customer Last Name is mandatory</Message>
</Errors>
</Response>