问题
In the latest .NET Core 2.1, an automatic validation for the model state validation is introduced (https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/#mvc).
Previously I could override the validation error response by the following code below:
public class ApiValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(new context.ModelState);
}
base.OnActionExecuting(context);
}
But now it no longer works. The validation errors is responded without entering the override method.
Anyone has any clue? Thanks.
回答1:
If you'd like to keep using the ApiController
attribute (which has other functions like disabling conventional routing and allowing model binding without adding [FromBody]
parameter attributes), you might be able to do it via this in your Startup.cs
file:
services.Configure<ApiBehaviorOptions>(opt =>
{
opt.SuppressModelStateInvalidFilter = true;
});
That will make it so that if the ModelState is invalid it won't automatically return a 400 error.
回答2:
I was recently asked by a friend about this and my approach was to replace the default ModalStateInvalidFilter
by a custom one.
In my test I've implemented the suggestion from here and then:
services.AddMvc(options =>
{
options.Filters.Add(typeof(ValidateModelAttribute));
});
services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });
来源:https://stackoverflow.com/questions/51125569/net-core-2-1-override-automatic-model-validation