【发布时间】: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