【问题标题】:how to handle bad request web api core with custome message?如何使用自定义消息处理错误请求 Web api 核心?
【发布时间】:2023-03-14 16:31:01
【问题描述】:

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

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

我搜索了但没有找到答案。

更新:

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

 return BadRequest (new {message = "Something went wrong"});

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

【问题讨论】:

  • 您的预期结果是什么?使用ProblemDetails 还是只返回400 的自定义错误消息,如herea simpler way 是什么意思?
  • 我只想返回Message{Message: "Error for ...."}

标签: asp.net-core-webapi webapi


【解决方案1】:

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

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

要禁用自动 400 行为,请将 Startup.ConfigureServices 中的 SuppressModelStateInvalidFilter 属性设置为 true:

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

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

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 2018-05-28
    • 2019-11-27
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2021-09-29
    相关资源
    最近更新 更多