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.
Alternatives to built-in attributes If you need validation not provided by built-in attributes, you can: Create custom attributes. Implement IValidatableObject.
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .
What is a ModelState C#? When we talk about ModelState , we mean ModelState property of the ControllerBase abstract class in the Microsoft. AspNetCore. Mvc namespace. It is of ModelStateDictionary type and it represents errors that come from two subsystems: model binding and model validation.
ModelState is a property of a Controller instance, and can be accessed from any class that inherits from Microsoft. AspNetCore. Mvc. Controller. The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.
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.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With