使用自定义验证属性进行模型验

时间:2017-03-17 17:11:27

标签: c# asp.net-web-api2 data-annotations modelstate model-validation

我正在使用model validation作为我的网络API,我将以下自定义模型作为示例

public class Address
{
    [Required(ErrorMessage = "The firstName is mandatory")]
    [EnhancedStringLength(100, ErrorCode = "1234556", ErrorMessage = "firstName must not exceed 100 characters")]
    public string FirstName { get; set; }
}

public sealed class EnhancedStringLengthAttribute : StringLengthAttribute
{
    public EnhancedStringLengthAttribute(int maximumLength) : base(maximumLength)
    {
    }

    public string ErrorCode { get; set; }
}

在我的模型验证过滤器中,我有以下作为示例

public class ModelValidationAttribute : ActionFilterAttribute
{

    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        if (actionContext.ModelState.IsValid)
        {
            return;
        }

        var errorViewModels = actionContext.ModelState.SelectMany(modelState => modelState.Value.Errors, (modelState, error) => new 
        {
            /*This doesn't work, the error object doesn't have ErrorCode property
            *ErrorCode = error.ErrorCode,
            **************************/
            Message = error.ErrorMessage,
        });


        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errorViewModels);

        await Task.FromResult(0);
    }
}

我想要实现的是当输入模型验证失败时(例如,在这种情况下FirstName字符串长度超过100),我想输出错误代码以及错误消息,如下所示:

[{"errorCode":"1234556","message":"firstName must not exceed 100 characters"}]

但问题是当访问过滤器中的ModelState时ErrorCode不可用,在这种情况下错误对象是类型System.Web.Http.ModelBinding.ModelError并且不包含errorcode属性,我该如何实现?

1 个答案:

答案 0 :(得分:0)

您正在扩展ActionFilterAttribute,但实际上您想扩展ValidationAttribute。

供参考:ASP.NET MVC: Custom Validation by DataAnnotation