模型验证与
问题描述:
我使用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属性,我该如何实现?
答
您正在扩展ActionFilterAttribute,但您确实想要扩展ValidationAttribute。
嘿,那不是我的意思。我想将我的自定义属性(ErrorCode)添加到验证属性,并且我希望它在ModelState中可用,清除? – Ming
我告诉你,这不是解决这个问题的正确方法。您将无法将该属性添加到ModelState中,而不会出现丑陋的解决方法。 – LaCartouche