ASP.NET Core Web API Interview Question #39
How can you customize automatic validation responses?
DTOs, Model Binding, Validation & API Responses Junior Beginner
Quick Interview Answer
ApiBehaviorOptions can customize the response produced when model validation fails. This is useful when an organization requires a consistent error envelope, correlation identifier, or additional metadata.
Detailed Explanation
ApiBehaviorOptions can customize the response produced when model validation fails. This is useful when an organization requires a consistent error envelope, correlation identifier, or additional metadata.
Customization should preserve meaningful HTTP semantics and enough field-level information for clients to correct invalid input.
Code Example
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var problem = new ValidationProblemDetails(
context.ModelState);
return new BadRequestObjectResult(problem);
};
});