ActionFilter中的ModelState-ASP .NET Core 2.1 API

时间:2018-07-06 22:48:03

标签: c# asp.net-core-2.0 asp.net-core-webapi 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; }

}

2 个答案:

答案 0 :(得分:8)

您的问题是由新功能Automatic HTTP 400 responses引起的:

  

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

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

当SuppressModelStateInvalidFilter属性设置为true时,默认行为被禁用。在services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

之后的Startup.ConfigureServices中添加以下代码
    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属性装饰控制器。