I successfully implemented FluentValidation in my WebApi project controller, which had only one HttpGet method. When I added another HttpGet method, I added a route attribute to both methods. those. [Route ("Method1")] and [Route ("Method2")].
ModelState now returns as true, regardless of whether I enter any data or not.
Here is my code.
WebApiConfig
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new ValidateModelStateFilter());
ValidateModelStateFilter
public class ValidateModelStateFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState); } } }
controller
[HttpGet] [Route("Method1")] public IHttpActionResult ReadAllMenusByApplication([FromUri] ReadAllMenusByApplicationInput input) { var result = new List<ApplicationMenu>(); ... }
Input object
using FluentValidation; using FluentValidation.Attributes; namespace MenuService.Models { [Validator(typeof(ReadAllMenusByApplicationInputValidator))] public class ReadAllMenusByApplicationInput { public ReadAllMenusByApplicationInput() { this.ApplicationName = string.Empty; }
}
c # asp.net-web-api fluentvalidation model-validation
John way
source share