如何自定义ValidationResult响应

时间:2018-07-18 00:25:15

标签: asp.net-web-api2

我正在构建一个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>

0 个答案:

没有答案