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

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

问题描述

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

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
}

我收到这样的错误消息:

I get an error back like this:

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

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

没有命中任何控制器代码.

Without the controller code ever being hit.

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

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:

如果您使用

[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天全站免登陆