I am using model validation for my web API and I have following custom model as an example
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; }
}
In my model validation filter I have following as an example
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);
}
}
What i would like to achieve is when input model fails validation (e.g. FirstName string length is more than 100 in this case) , I would like to output error code as well as error message, like this:
[{"errorCode":"1234556","message":"firstName must not exceed 100 characters"}]
But the problem is the ErrorCode isn't available when access the ModelState in the filter, the error object in this case is type System.Web.Http.ModelBinding.ModelError
and doesn't contain errorcode property, how can i achieve this?