2

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?

Ming
  • 730
  • 2
  • 8
  • 23

1 Answers1

0

You are extending ActionFilterAttribute but you actually want to extend ValidationAttribute.

For reference: ASP.NET MVC: Custom Validation by DataAnnotation

Community
  • 1
  • 1
LaCartouche
  • 121
  • 1
  • 11
  • Hey, that is not what I mean. I want to add my custom property (ErrorCode) to validation attribute , and I want it to be available in the ModelState, clear? – Ming Mar 20 '17 at 08:27
  • And I'm telling you that it's not the right way to approach that problem. You will not be able to add that property to the ModelState without ugly workarounds. – LaCartouche Mar 20 '17 at 17:23