我需要从“ ModelState”中捕获错误以发送个性化消息。问题是,如果UserDTO的属性具有属性“ Required”,则永远不会执行过滤器。如果将其删除,请输入过滤器,但modelState有效
[HttpPost]
[ModelState]
public IActionResult Post([FromBody] UserDTO currentUser)
{
/*if (!ModelState.IsValid)
{
return BadRequest();
}*/
return Ok();
}
public class ModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext currentContext)
{
if (!currentContext.ModelState.IsValid)
{
currentContext.Result = new ContentResult
{
Content = "Modelstate not valid",
StatusCode = 400
};
}
else
{
base.OnActionExecuting(currentContext);
}
}
}
public class UserDTO
{
[Required]
public string ID { get; set; }
public string Name { get; set; }
}
答案 0 :(得分:8)
您的问题是由新功能Automatic HTTP 400 responses引起的:
验证错误会自动触发HTTP 400响应。
因此,如果要自定义验证错误,则需要禁用此功能。
当SuppressModelStateInvalidFilter属性设置为true
时,默认行为被禁用。在services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure<ApiBehaviorOptions>(options => {
options.SuppressModelStateInvalidFilter = true; });
答案 1 :(得分:0)
在ASP.NET Core 2.1中,您还可以使用InvalidModelStateResponseFactory
的{{1}}中的ConfigureServices
参数更改验证错误响应:
Startup.cs
例如,此配置返回带有services.Configure<ApiBehaviorOptions>(options =>
options.InvalidModelStateResponseFactory = actionContext =>
new BadRequestObjectResult(
new
{
error = string.Join(
Environment.NewLine,
actionContext.ModelState.Values.SelectMany(v => v.Errors.Select(x => x.ErrorMessage)).ToArray()
)
}
)
);
字段的对象,其中合并了所有验证错误。
在这种情况下,不需要ValidationAttribute,但是您应该使用error
属性装饰控制器。