gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:08 25 4
gpt4 key购买 nike

我正在使用 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);
}
}

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

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

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

最佳答案

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

供引用:ASP.NET MVC: Custom Validation by DataAnnotation

关于c# - 使用自定义验证属性进行模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com