C# ActionFilter中的ModelState-ASP.NET核心2.1 API

C# ActionFilter中的ModelState-ASP.NET核心2.1 API,c#,asp.net-core-2.0,asp.net-core-webapi,asp.net-core-2.1,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();

我需要捕获“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; }

}
    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });

您的问题是由以下新功能引起的:

    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });
验证错误会自动触发HTTP 400响应

    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });
因此,如果要自定义验证错误,则需要禁用此功能

    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });
当SuppressModelStateInvalidFilter属性设置为
true
时,将禁用默认行为。在
services.AddMvc()之后的Startup.ConfigureServices.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)中添加以下代码

    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });
services.Configure(选项=>{
options.SuppressModelStateInvalidFilter=true;});

在ASP.NET Core 2.1中,您还可以在
Startup.cs
中使用
ConfigureServices
中的
InvalidModelStateResponseFactory
参数更改验证错误响应:

    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });
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()
                )
            }
        )
);
services.Configure(选项=>
options.InvalidModelStateResponseFactory=actionContext=>
新的BadRequestObjectResult(
新的
{
error=string.Join(
环境,新线,
actionContext.ModelState.Values.SelectMany(v=>v.Errors.Select(x=>x.ErrorMessage)).ToArray()
)
}
)
);
例如,此配置返回包含
错误
字段的对象,其中包含所有验证错误。

在这种情况下,不需要ValidationAttribute,但您应该使用
[ApiController]
属性来装饰控制器。

我尝试使用最新的ASPNET Core 2.1,但它似乎没有起到任何作用。我正试图通过OnPostAsync在2.1 Razor页面上的“dotnet”捕获控制台中的无效模型消息。有人知道是否有可能为单个操作阻止此操作吗?该功能确实很有帮助,但当我需要在验证之前进行一些预处理时,我有一个操作。是否有方法捕获异常?
    services.Configure<ApiBehaviorOptions>(options => {    
options.SuppressModelStateInvalidFilter = true;  });