繁体   English   中英

具有自定义验证属性的模型验证

[英]Model validation with custom validation attribute

我正在为我的Web 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属性,我该如何实现?

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

供参考: ASP.NET MVC:通过DataAnnotation进行自定义验证

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM