I am working on an ASP.NET Core 6 Web API project. We use Fluent Validation. How can I return custom response. Please advice.
I would like to send custom response on different validation error such as page, limit, date etc
This is the response I get by default:
{
"type": "",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-097c689850af328c49705cea77fc6fbd-0c7defe165d9693f-00",
"errors": {
"Page": [
"Page value should be greater than 0"
],
"Limit": [
"Limit value should be greater than 0"
]
}
}
And this is the response I would like to get:
{
"traceId": "e45b3398-a2a5-43eb-8851-e45de1184021",
"timestamp": "2021-06-28T00:32:06.548Z",
"errors": [
{
"errorCode": "Contract Violation",
"message": "Page should be greater than 0",
"priority": "MEDIUM",
"properties": {
"name": "string",
"value": "string"
}
}
]
}
This is my code:
public async Task<IActionResult> Get([FromQuery] DataParameter input)
{
}
public class DataParameter
{
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int Page { get; set; }
public int Limit { get; set; }
}
public class QueryParameterValidator : AbstractValidator<QueryParameter>
{
public QueryParameterValidator()
{
RuleFor(model => model.Page)
.GreaterThan(0)
.WithMessage("Page value should be greater than 0");
RuleFor(model => model.Limit)
.GreaterThan(0)
.WithMessage("Limit value should be greater than 0");
RuleFor(model => model.StartDate)
.Matches(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$")
.WithMessage("Transaction from date should be in the pattern of YYYY-MM-DD");
RuleFor(model => model.EndDate)
.Matches(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$")
.WithMessage("Transaction to date should be in the pattern of YYYY-MM-DD");
}
}

ValidationProblemDetails.