c# - .net 核心 API 中的无效模型类属性错误

标签 c# asp.net-core-webapi

当我将 post 方法从 postman 发送到具有无效模型类属性的 .net 核心 API 时,例如模型类包含长字段但我发送字符串值时,我在 postman 中收到错误但我在 catch 方法中没有收到错误

    [HttpPost]
    public async Task<IActionResult> CalculateFee(CollegeGetModel collegeModel)
    {
        try
        {
            return await _collegeService.CalculateFee(collegeModel);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

模型类是

public class CollegeGetModel {
   public long Id {get;set;}
   public string Name {get;set;}
}

返回的错误信息是

{
"errors": {
    "Id": [
        "Error converting value \"str\" to type 'System.Int64'. Path 'Id', line 2, position 20."
    ]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "0HLTA1MNU7LV5:00000001"
}

我在 Controller catch 方法中没有收到此错误消息。如何在 Controller 方法中获取此错误消息?

最佳答案

在 ASP.NET Core Web API 中,模型绑定(bind)发生在操作方法中的代码执行之前。因此,如果存在模型状态验证错误,它会导致自动 400 响应代码,因此它不会在操作方法内执行您的 catch block 。

引用这个linkthis了解更多详情。

编辑:删除链接 ASP.Net Web Api 2: HTTP Message Lifecycle

更新:您可以通过在 Startup.ConfigureServices 中添加以下代码来禁用此自动 400 响应:

ASP.Net Core 2.1

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

网络核心 3.1

services.AddControllers()
        .ConfigureApiBehaviorOptions(options =>
        {
            options.SuppressConsumesConstraintForFormFileParameters = true;
            options.SuppressInferBindingSourcesForParameters = true;
            options.SuppressModelStateInvalidFilter = true;
            options.SuppressMapClientErrors = true;
            options.ClientErrorMapping[404].Link =
                "https://httpstatuses.com/404";
        });

关于c# - .net 核心 API 中的无效模型类属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60071028/

相关文章:

javascript - .NET Core Web API 路由和 GET 请求

c# - 在 C# 中将对象数组转换为另一种类型的简单方法

azure - .NET Core Web API 部署到 Azure 后无法工作

c# - "Malformed Packet: TNS"从Oracle数据库检索数据

c# - 如何在调试 ASP.net 程序时访问堆栈帧?

asp.net - 在 ASP.Net Core 2.2 中定义不同的 API 以接受不同的大小限制

c# - 使用属性属性来定义要使用的 JsonConverter

c# - 如何阻止从 Controller 继承的类的 OnActionExecuting 中执行操作

c# - 如何将控制台输出管道输出到出现的 ASP.NET 页面?

C# Reg_Binary 和 BATCH