在 .NET Core 2.1 中使用 [FromBody] 时处理模型绑定错误 [英] Handling Model Binding Errors when using [FromBody] in .NET Core 2.1

查看:63
本文介绍了在 .NET Core 2.1 中使用 [FromBody] 时处理模型绑定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何拦截和处理 .net 核心中的模型绑定错误.

I am trying to understand how I can intercept and handle model binding errors in .net core.

我想这样做:

    // POST api/values
    [HttpPost]
    public void Post([FromBody] Thing value)
    {
        if (!ModelState.IsValid)
        {
            // Handle Error Here
        }
    }

事物"的模型在哪里:

public class Thing
{
    public string Description { get; set; }
    public int Amount { get; set; }
}

但是,如果我传入一个无效的金额,例如:

However if I pass in an invalid amount like:

{ 
   "description" : "Cats",
   "amount" : 21.25
}

我收到这样的错误:

{"amount":["输入字符串 '21.25' 不是有效整数.路径 'amount',第 1 行,位置 38."]}

{"amount":["Input string '21.25' is not a valid integer. Path 'amount', line 1, position 38."]}

没有命中控制器代码.

如何自定义发回的错误?(基本上我需要将这个序列化错误包装在一个更大的错误对象中)

How can I customise the error being sent back? (as basically I need to wrap this serialisation error in a larger error object)

推荐答案

所以,我之前错过了这个,但我在这里找到了:

So, I missed this before but I have found here:

https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.2#automatic-http-400-responses

如果你使用

[ApiController] 

控制器上的属性,它会自动处理序列化错误并提供 400 响应,相当于:

attribute on your controller, it will automatically handle serialisation errors and provide the 400 response, equivalent to:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

您可以像这样在 Startup.cs 中关闭此行为:

You can turn this behaviour off in the Startup.cs like this:

services.AddMvc()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

如果您想自定义响应,更好的选择是使用 InvalidModelStateResponseFactory,这是一个接受 ActionContext 并返回 IActionResult 的委托,该 IActionResult 将被调用以处理序列化错误.

If you are looking to customise the response, a better option is to use a InvalidModelStateResponseFactory, which is a delegate taking an ActionContext and returning an IActionResult which will be called to handle serialisation errors.

看这个例子:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = actionContext => 
    {
        var errors = actionContext.ModelState
            .Where(e => e.Value.Errors.Count > 0)
            .Select(e => new Error
            {
            Name = e.Key,
            Message = e.Value.Errors.First().ErrorMessage
            }).ToArray();

        return new BadRequestObjectResult(errors);
    }
});

这篇关于在 .NET Core 2.1 中使用 [FromBody] 时处理模型绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆