如何使用客户消息处理错误请求 Web api 核心?

MrJ*_*bin 0 asp.net-core-webapi webapi

我有类似的问题。\n是否有更简单的方法来处理输入数据类型错误?

\n\n

https://coderethinked.com/customizing-automatic-http-400-error-response-in-asp-net-core-web-apis/

\n\n

我搜索但没有找到答案。

\n\n

更新:

\n\n

我从微软的例子中找到了一个解决方案:\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0

\n\n
 return BadRequest (new {message = "Something went wrong"});\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是\n当字段为[必填]时模型时,在运行服务之前会调用错误 400。有没有办法解决句柄模型的 400 错误?

\n

Rya*_*yan 5

但是当字段处于 [Required] 模型中时,在运行服务之前会调用错误 400。有没有办法解决句柄模型的 400 错误?

该[ApiController]属性使模型验证错误自动触发 HTTP 400 响应。

要禁用自动 400 行为,请SuppressModelStateInvalidFilter在以下位置中将该属性设置为 true Startup.ConfigureServices:

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

请参阅https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1#disable-automatic-400-response