I'm developing an ASP.NET WebApi2 (.NET 4.7.2) with Owin and Autofac as IOC container. The Dtos shall get validated with FluentValidation before reaching the controller. Here is my project configuration:
public class Startup
{
public void Configuration(IAppBuilder app)
{
...
var config = new HttpConfiguration();
config.Filters.Add(new ValidateDtoStateFilter());
...
FluentValidationModelValidatorProvider.Configure(config);
...
}
}
Validate dto state filter:
public class ValidateDtoStateFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
throw new ValidationException(actionContext.ModelState
.SelectMany(ms => ms.Value.Errors
.Select(er => new ValidationFailure(ms.Key.Split('.')[1].FromPascalToCamelCase(), er.ErrorMessage))));
}
}
}
Autofac builder configuration:
builder.RegisterAssemblyTypes(typeof(MyDtoValidator).Assembly)
.Where(t => t.Name.EndsWith("Validator"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>();
builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
Autofac validator factory:
public class AutofacValidatorFactory : ValidatorFactoryBase
{
private readonly IComponentContext _context;
public AutofacValidatorFactory(IComponentContext context)
{
_context = context;
}
public override IValidator CreateInstance(Type validatorType)
{
object instance;
return _context.TryResolve(validatorType, out instance) ? instance as IValidator : null;
}
}
It works fine with POST or PUT endpoints where the dto comes [FromBody]
in the requets payload. It does not work with [FromUri]
dtos, e.g. in a GET request. The validator will be created by Autofac, but in OnActionExecuting
of ValidateDtoStateFilter
actionContext.ModelState
is always true, no matter if the supplied data is valid or not.
How can I achieve that [FromUri]
dtos get validated by the FluentValidation middleware as well?
Update
The issue does not occur any more without my having changed anything.