gpt4 book ai didi

c# - 在 .NET Core 2.1 中使用 [FromBody] 时处理模型绑定(bind)错误

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:12 24 4
gpt4 key购买 nike

我正在尝试了解如何拦截和处理 .net Core 中的模型绑定(bind)错误。

我想这样做:

    // 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; }
}

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

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

我收到这样的错误:

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

没有 Controller 代码被命中。

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

最佳答案

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

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

如果你使用

[ApiController] 

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

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

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

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

如果您希望自定义响应,更好的选择是使用 InvalidModelStateResponseFactory,它是一个采用 ActionContext 并返回将被调用以处理序列化错误的 IActionResult 的委托(delegate)。

看这个例子:

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

关于c# - 在 .NET Core 2.1 中使用 [FromBody] 时处理模型绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com