c# - 发布对象数组时如何修复反序列化错误
问题描述
"Message": "请求无效。", "ModelState": { "notification": [
“无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'iBasement.Models.Notification',因为该类型需要 JSON 对象(例如 {\"name\":\"value\"})正确反序列化。\r\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\"name\":\"value\"})或将反序列化的类型更改为数组或实现集合接口的类型“
尝试使用这样的数组调用帖子:
POST /api/Notifications/UpdateMac HTTP/1.1
Host: localhost:56005
Content-Type: application/json
User-Agent: PostmanRuntime/7.17.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 4ac88367-af2c-48e8-99a0-b89fba2ea76a,c1f78db8-e040-4675-9103-5c9c41273c24
Host: localhost:56005
Accept-Encoding: gzip, deflate
Content-Length: 507
Connection: keep-alive
cache-control: no-cache
[
{
"Id": 1,
"MacAddress": "f8:f0:05:ed:1d:28",
"Destination": "janedoe@gmail.com",
"SendAlertTypes": "0,1,4,5,6"
},
{
"Id": 6,
"MacAddress": "f8:f0:05:ed:1d:28",
"Destination": "johndoe@hotmail.com",
"SendAlertTypes": "0,1,2,3,4,5,6"
},
{
"Id": 99,
"MacAddress": "f8:f0:05:ed:1d:28",
"Destination": "4012221234@vtext.com",
"SendAlertTypes": "0,1,2,3,4,5,6"
}
]
[Route("~/UpdateMac")]
public async Task<HttpResponseMessage> PostNotifications([FromBody]List<Notification> notifications)
{
//do list operations..
}
public class Notification
{
public int Id { get; set; }
public string MacAddress { get; set; }
public string Destination { get; set; }
//"0,1,2,3,6" <-- 4, 5, & 7+ would be omitted
public string SendAlertTypes { get; set; }
}
解决方案
你有几个问题,但没有一个是你得到的例外。
- 主机标头重复,应将其删除。
- 路由
代码示例正在使用[Route("~/UpdateMac")]
,这意味着“忽略所有路由前缀属性”,因此,您只能调用此操作,而之前没有任何其他路径。
不会工作:POST /api/Notifications/UpdateMac HTTP/1.1
会工作:POST /UpdateMac HTTP/1.1
如果您仍想使用完整的/api/Notifications/UpdateMac
路由,这里有几种方法
- 更改
[Route("~/UpdateMac")]
为[Route("api/Notifications/UpdateMac")]
。 - 装饰控制器
[RoutePrefix("api/Notifications")]
并将动作更改为[Route("UpdateMac")]
(不带波浪号)。
在这些实验中,我都没有遇到反序列化问题,这可能意味着客户端以某种方式产生不同的请求,尝试使用Fiddler或curl直到在PostMan中找到不匹配。
推荐阅读
- php - 使用 Mercure Hub 的问题
- sql - 不确定我是否理解使用逗号和 table(...) 的 Snowflake FROM 语法
- c# - IMediator 模拟从 xUnit 测试中的控制器类返回 null
- html - 如何在表格的 HTML 页脚中显示页码
- youtube - 是否可以跟踪使用会员合作伙伴的 youtube 视频链接收到的喜欢和订阅
- typescript - 从数组初始化对象的属性 - 内联
- azure - 无法访问我创建的 azure bot 的秘密
- python - 通过排除表来处理 Automap 错误
- php - 为什么我的页面使用表单过滤器冻结
- php - 不推荐使用:使用 php 7 不推荐使用函数 ereg()