首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在发布对象数组时修复反序列化错误

如何在发布对象数组时修复反序列化错误
EN

Stack Overflow用户
提问于 2019-09-14 11:02:45
回答 1查看 565关注 0票数 0

“消息”:“请求无效”,"ModelState":{“通知”:[

“无法将当前的JSON数组(例如,1,2,3)反序列化为'iBasement.Models.Notification‘类型,因为该类型需要一个JSON对象(例如{\”name\“:\”value\})才能正确反序列化。\r\n要修复此错误,可以将JSON更改为JSON对象(例如{\“name\”:\“value\}),或者将反序列化类型更改为数组或实现集合接口(例如ICollection、IList)的类型,比如可以从JSON数组反序列化的列表。还可以将JsonArrayAttribute添加到类型中,以强制它从JSON数组反序列化。\r\nPath‘,第1行,位置1。“

试图用这样的数组调用post:

代码语言:javascript
复制
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; }


}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-17 10:36:03

你有几个问题,但没有一个是你得到的例外。

  1. 重复的主机头,这应该被删除。
  2. 路由 代码示例使用的是[Route("~/UpdateMac")],这意味着“忽略所有路由前缀属性”,因此,您只能调用此操作,而之前没有任何其他路径。 不起作用:POST /api/Notifications/UpdateMac HTTP/1.1 将工作:POST /UpdateMac HTTP/1.1

如果您仍然想使用完整的/api/Notifications/UpdateMac路由,下面是几种方法

  1. [Route("~/UpdateMac")]更改为[Route("api/Notifications/UpdateMac")]
  2. [RoutePrefix("api/Notifications")]装饰控制器,并将操作更改为[Route("UpdateMac")] (没有倾斜)。

在所有这些实验中,我都没有遇到反序列化问题,这可能意味着客户端以某种方式产生不同的请求,可以尝试使用Fiddlercurl,直到发现PostMan中的不匹配为止。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57934853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档