ASP Net Core Web API,我正在尝试为模型验证器返回自定义响应。但是,当必填字段不在请求中时,不会调用ValidateModelFilter。
ValidateModelFilter.cs
public class ValidateModelFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var response = new Model
{
error = context.ModelState.ToString()
};
context.Result = new BadRequestObjectResult(response);
}
}
}
启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.Filters.Add(typeof(ValidateModelFilter)));
}
我得到这样的回应
{
"errors": {
"Firstname": [
"The Firstname field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|e6752549-4142e91f1074e978."
}
我想返回一个像
{
"error": "The Firstname field is required."
}
该链接显示了我们如何禁用默认的Model Binding Exception过滤器,该过滤器返回400错误并使管道短路。只有这样,我们的自定义ActionFilterAttribute中的OnActionExecuting方法才真正被执行。然后一切都会按预期进行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句