.NET Core捕获中间件中的Json反序列化错误 [英] .NET Core Catch Json Deserialization Error In Middleware
问题描述
我敢肯定我缺少明显明显的东西.
I'm certain I'm missing something patently obvious.
是否可以在.NET Core的默认中间件/反序列化器中处理JSON反序列化错误?我需要确保特定值是JSON原语而不是对象/数组.如果不是原始类型,我想终止请求并在到达控制器之前返回适当的状态代码.
Is it possible to handle JSON deserialization errors in .NET Core's default middleware/deserializer? I need to be sure that a particular value is a JSON primitive and not an object/array. If it's not a primitive, I'd like to terminate the request and return the appropriate status code before it gets to the controller.
控制器:
[HttpPost]
public IActionResult Post([FromBody] List<MyType> myTypes)
{
// Logic ....
return Created(new Uri("some-location/", UriKind.Relative), someValue);
}
请求正文:
[
{
"prop1": "some value",
"prop2": "some value",
"prop3": null
},
{
"prop1": "some value",
"prop2": "some value",
"prop3": {
"prop3-1": "some value"
}
}
]
MyType
构造函数检查传入的参数,并在出现问题时引发异常. MyType
中的prop3
是dynamic
字段.我已经验证了对请求正文中的第二项进行反序列化时是否引发了异常.
The MyType
constructor inspects the arguments passed in and throws an exception if there's a problem. prop3
in MyType
is a dynamic
field. I've verified that the exception is being thrown when the second item in the request body is deserialized.
这一切感觉非常简单,但我只是找不到在哪里访问默认的反序列化器.
This all feels pretty straightforward but I just can't find where to access the default deserializer.
我尝试了此,并且确实会捕获错误,但仅在请求已将其发送到控制器之后.
I tried this and it does catch errors but only after the request has made it into the controller.
有没有办法在JSON注释中处理此问题?我浏览了Newtonsoft文档,但没有发现任何问题.
Is there a way to handle this in JSON annotations? I looked through the Newtonsoft docs but nothing jumped out.
推荐答案
在此处查看文档: https://docs. microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1 我认为您正在寻找的是AddJsonOptions()
Looking at the documentation here: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1 I think what you are looking for is the AddJsonOptions()
在Startup.cs中:
in Startup.cs:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Error;
});
这不会引发异常,但是它将无法绑定,因此myTypes变为null.
This will not throw an exception, but it will fail to bind, so myTypes becomes null.
然后您可以添加一个空支票
Then you can just add a null check
[HttpPost]
public IActionResult Post([FromBody] List<MyType> myTypes)
{
if(myTypes == null)
{
return BadRequest();
}
// Logic ....
return Created(new Uri("some-location/", UriKind.Relative), someValue);
}
这篇关于.NET Core捕获中间件中的Json反序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!