ActionFilter的ModelState - ASP .NET Core 2.1 API

ave*_*che 3 c# asp.net-core-webapi asp.net-core-2.0 asp.net-core-2.1

我需要从"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; }

}
Run Code Online (Sandbox Code Playgroud)

Tao*_*hou 11

您的问题是由新功能自动HTTP 400响应引起的:

验证错误会自动触发HTTP 400响应.

因此,如果要自定义验证错误,则需要禁用此功能.

当SuppressModelStateInvalidFilter属性设置为时,将禁用默认行为true.之后在Startup.ConfigureServices中添加以下代码services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });
Run Code Online (Sandbox Code Playgroud)