我正在开发一个ASP.NET Core 6 Web API项目,我们使用Fluent Validation。如何返回自定义响应?请给予建议。
我想在不同的验证错误(例如页面、限制、日期等)上发送自定义响应。
这是我默认收到的响应:
{
"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"
]
}
}
以下是我希望得到的回复:
{
"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"
}
}
]
}
这是我的代码:
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");
}
}