Search code examples
asp.net-core-webapi.net-core-3.1

How to make Web API return all errors for the validated model?


ModelState returns only 1 error at a time when validation occurs. How to force Web API to return all errors at once.

 services.AddControllers()
            .ConfigureApiBehaviorOptions(setupAction =>
            {
                setupAction.InvalidModelStateResponseFactory = context =>
                {
                      // context.ModelState here always contains only 1 error, even if I have more invalid fields in 
                }
            };

Solution

  • Considering your scenario, it can be said that,

    In InvalidModelStateResponseFactory there is a constructor callled ModelStateDictionary() under this you would get ErrorCount which can get you number of error.

    But if you are expecting you would get all the error details together, you cannot do that. It will always fetch first one and terminates execution and entered to your custom InvalidModelStateResponseFactory middleware.

    Note: So when any error encounters it terminates and return rather executing further as a results we always get first one. You could get our official document here

    Hope it would help you to guide you through.