Search code examples
c#asp.net-coreasp.net-web-apidata-annotationsvalidationattribute

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


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.


Solution

  • 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){};
                            }; });