Ish*_*mas 4 c# fluentvalidation .net-core asp.net-core asp.net-core-webapi
我用来FluentValidation验证我的输入ASP.NET Core 3.1 Web API。我用“自动”方式来做。所以在我的Startup课堂上我有这个:
services.AddControllers()
.AddFluentValidation(opt =>
{
opt.RegisterValidatorsFromAssemblyContaining(typeof(UserInputValidator));
});
Run Code Online (Sandbox Code Playgroud)
这样,FluentValidation就可以神奇地验证上述程序集的所有输入,而无需其他代码。非常甜蜜,但是......响应格式与我返回时使用的响应格式不同BadRequest。这是 FluentValidation 格式:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3b037c98-40d28ab8553d6989.",
"errors": {
"UserId": [
"'User Id' must be greater than '0'."
],
"Score": [
"'Score' must be between 0 and 500. You entered 900."
]
}
}
Run Code Online (Sandbox Code Playgroud)
我宁愿有:
{
"code": 123456,
"message": "One or more validation errors occurred.",
"errors": [
"'User Id' must be greater than '0'.",
"'Score' must be between 0 and 500. You entered 900."
]
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,是否可以覆盖它?
我有一个想法,但不确定这是否是一种好的做法(甚至可能),但如果FluentValidation不返回它BadRequest response会抛出异常,我将能够在中间件中捕获它并重新格式化。
不管怎样,FluentValidation很受欢迎,.NET Core WebAPI很受欢迎。我很难相信“忍者开发人员”会只使用第三方工具提供的响应,这与他们的响应格式不匹配。然而,我没有看到很多如何修复它的材料(即使在FluentValidation网站上也是如此。我错过了吗?
您可以通过使用asp.net core 中的过滤器来实现此结果。完成 Fluent Validation 设置后,您必须编写一个过滤器。
public class CustomValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0)
.SelectMany(v => v.Errors)
.Select(v => v.ErrorMessage)
.ToList();
var responseObj = new
{
Code= 123456,
Message = "One or more validation errors occurred.",
Errors = errors
};
context.Result = new JsonResult(responseObj)
{
StatusCode = 200
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在启动类中定义这个过滤器。
services.AddMvc(options =>
{
options.Filters.Add(typeof(CustomValidationAttribute));
})
.AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining<AnyValidatorClass>());
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
Run Code Online (Sandbox Code Playgroud)