I would like to apply class validation on the response body/output of my .NET WebApi in the same way .NET automatically validates the request body using class validation.
public class RequestAndResponseDto
{
[Required]
public string SomeProperty { get; set; }
}
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
[HttpPost]
Task<RequestAndResponseDto> Post([FromBody] RequestAndResponseDto requestBody)
{
return new RequestAndResponseDto();
}
}
I would like an exception to be thrown, because SomeProperty is a required property. The same would go for other validations, such as MinLength etc.
The solution should be applied to all controllers and all methods in the application. How would I achieve this without adding custom logic in each endpoint?

To apply class validation on the response body/output globally across all controllers and methods in your .NET Web API, you can create and register an action filter that performs model validation on the action result. This approach allows you to reuse the validation logic without modifying each endpoint individually.
Here's how you can achieve this:
First, create a custom action filter that checks if the action result is of the type that needs validation (e.g., your DTOs) and then performs the validation using the Validator class.
Next, you need to register this action filter globally so it's applied to all controllers and actions. You can do this in the Startup.cs or wherever you configure services in your application.
This setup ensures that your response DTOs are validated just like your request DTOs. If the validation fails, a BadRequest response is returned with the validation errors. Note: This approach validates the response before it's sent back to the client. It's important to ensure that your application logic correctly handles cases where the response data might not pass validation, as this could indicate a flaw in your application's data handling or business logic.