Nit*_*han 3 c# asp.net-core-webapi
当我从邮递员向 .net 核心 API 发送具有无效模型类属性的 post 方法时,例如模型类包含长字段但我发送字符串值,我在邮递员中收到错误,但在 catch 方法中没有收到错误
[HttpPost]
public async Task<IActionResult> CalculateFee(CollegeGetModel collegeModel)
{
try
{
return await _collegeService.CalculateFee(collegeModel);
}
catch (Exception ex)
{
return ex.Message;
}
}
Run Code Online (Sandbox Code Playgroud)
和模型类是
public class CollegeGetModel {
public long Id {get;set;}
public string Name {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
返回的错误信息是
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
我没有在控制器捕获方法中收到此错误消息。如何在控制器方法中获取此错误消息?
在 ASP.NET Core Web API 中,模型绑定发生在你的代码操作方法执行之前。因此,如果存在模型状态验证错误,则会导致自动 400 响应代码,因此它不会在 action 方法中执行您的 catch 块。
编辑:删除链接ASP.Net Web Api 2:HTTP 消息生命周期
更新:您可以通过在 Startup.ConfigureServices 中添加以下代码来禁用此自动 400 响应:
ASP.NET 核心 2.1
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressConsumesConstraintForFormFileParameters = true;
options.SuppressInferBindingSourcesForParameters = true;
options.SuppressModelStateInvalidFilter = true;
});
Run Code Online (Sandbox Code Playgroud)
ASP.NET 核心 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";
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1549 次 |
| 最近记录: |