You can create a Validator for the ExampleModel with FluentValidation package.
Here is the example:
public class ExampleModelValidator : AbstractValidator<ExampleModel>
{
public ExampleModelValidator()
{
RuleFor(e => e.ExampleGuid)
.Must(guid => guid.ToString().lenght > 0)
.When(e => e.ExampleGuid.HasValue)
.WithMessage("Must be a valid GUID");
}
}
This will validate your model before the endpoint body.
Additionaly I personally like to add this piece of code in my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ExampleModelValidator>())
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var errorsList = string.Join(" | ", context.ModelState.Values.SelectMany(v => v.Errors).Select(err => err.ErrorMessage).ToArray());
return new BadRequestObjectResult(errorsList);
};
});
}
This will return all validation messages separated by pipe and BadRequest as response.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…