当我将 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 。
编辑:删除链接 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/