且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 .NET Core 自定义 Web API 中的错误响应?

更新时间:2023-02-15 10:08:21

正如 Chris 分析的那样,您的问题是由 自动 HTTP 400回复.

As Chris analyzed, your issue is caused by Automatic HTTP 400 responses.

对于快速解决方案,您可以通过

For the quick solution, you could suppress this feature by

services.AddMvc()
        .ConfigureApiBehaviorOptions(options => {
            options.SuppressModelStateInvalidFilter = true;
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

对于一种有效的方法,您可以遵循 Chris 的建议,如下所示:

For an efficient way, you could follow the suggestion from Chris, like below:

services.AddMvc()
        .ConfigureApiBehaviorOptions(options => {
            //options.SuppressModelStateInvalidFilter = true;
            options.InvalidModelStateResponseFactory = actionContext =>
            {
                var modelState = actionContext.ModelState.Values;
                return new BadRequestObjectResult(FormatOutput(modelState));
            };
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

而且,您无需再在操作中定义以下代码.

And, there isn't any need to define the code below any more in your action.

if (!ModelState.IsValid)
{
    return BadRequest(FormatOutput(ModelState.Values));
}