繁体   English   中英

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

[英]Invalid model class property error in .net core API

当我从邮递员向 .net 核心 API 发送具有无效模型类属性的 post 方法时,例如模型类包含长字段但我发送字符串值,我在邮递员中收到错误,但在 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"
}

我没有在控制器捕获方法中收到此错误消息。 如何在控制器方法中获取此错误消息?

在 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;
});

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";
        });

在 ASP.NET 核心 Web API 中,任何无效的模型绑定都存储在 ModelState 属性中。 但是,如果 ModelState 无效,AspNet 核心会通过在 Controller 类顶部使用 ApiController 属性自动返回错误请求。

要拦截请求,您必须注释掉 ApiController 属性。

[Route("api/[controller]")]
//[ApiController]
public class HomeController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CalculateFee(CollegeGetModel collegeModel)
    {
        if (!ModelState.IsValid)
        {
            // Do whatever you want here. E.g: Logging
        }
        return await _collegeService.CalculateFee(collegeModel);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM