exceptionnotfound / WebApiValidationDemo

https://www.exceptionnotfound.net/custom-validation-in-asp-net-web-api-with-fluentvalidation/
12 stars 9 forks source link

Fluent Validation not working with WebAPI Route attribute #1

Open johnway2 opened 8 years ago

johnway2 commented 8 years ago

If I add a [Route("routename")] attribute to a method and then submit a request to the controller without providing any parameters, the input class never gets instantiated and none of the fluentValidation rules fire, so my ModelState.IsValid = true. This allows the request to flow to my controller method, but the object is null and this causes an error. If I remove the [Route()] attribute, everything works fine. The object instantiates, the rules run and my request is returned to the client with the appropriate error messages.

I have added a check to my Validator, but it feels really clunky and I was hoping there was a better fix.


public class ValidateModelStateFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionArguments["input"] == null)
            {
                var badItem = new System.Web.Http.ModelBinding.ModelState();
                badItem.Errors.Add("Empty Object");
                actionContext.ModelState.Add("test", badItem);
            }
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }

Please refer to http://stackoverflow.com/questions/36924316/fluentvalidation-doesnt-work-when-using-webapi-route-attribute and https://github.com/JeremySkinner/FluentValidation/issues/157

exceptionnotfound commented 8 years ago

Two things I'd need clarification on:

  1. What do you mean by "without providing any parameters"? Could you give me an example URL that fits your use case?
  2. I've looked over the StackOverflow question and FluentValidation issue, and I'm not seeing anything obvious. Do you have a sample project somewhere that shows this issue?