【问题标题】:Model validation with custom validation attribute具有自定义验证属性的模型验证
【发布时间】:2017-03-17 17:11:26
【问题描述】:

我将 model validation 用于我的 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);
    }
}

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 嘿,我不是这个意思。我想将我的自定义属性 (ErrorCode) 添加到验证属性,并且我希望它在 ModelState 中可用,清楚吗?
    • 我告诉你,这不是解决这个问题的正确方法。如果没有丑陋的解决方法,您将无法将该属性添加到 ModelState。
    猜你喜欢
    • 2012-12-08
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2014-03-23
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多