ValidationResult to send 409 conflict status code ASP.NET Core Web Api

1.3k Views Asked by At

Is it possible to send HttpStatusCode.Conflict(409) from ValidationResult method of System.ComponentModel.DataAnnotations

By default it is returning HttpStatusCode.BadRequest(400). is there any possible way to send different status codes with ValidationResult method.

1

There are 1 best solutions below

2
ChizT On BEST ANSWER

Since you are using asp.net core you can override the ApiController attribute behavior in the StartUp > ConfigureServices

services.AddControllers()
                    .ConfigureApiBehaviorOptions(options => {
                        options.InvalidModelStateResponseFactory = context =>
                        {
                            var problemDetails = new ValidationProblemDetails(context.ModelState)
                            {
                                Status = StatusCodes.Status409Conflict,                            
                            };

                            return new UnprocessableEntityObjectResult(problemDetails){};
                        }; });