【问题标题】:ASP.NET MVC POST Method Not Receiving JSON DictionaryASP.NET MVC POST 方法不接收 JSON 字典
【发布时间】:2017-09-08 14:57:05
【问题描述】:

我有一个发布到我的 ASP.NET MVC 4 HttpPost 方法的移动应用程序,每次它接收到数据时,它都没有接收到正确的数据。

[HttpPost]
public void NewItems(Dictionary<string, List<Dictionary<string, string>>> newItemsDictionary) 
{
}

我的 RouteConfig 设置如下:

routes.MapRoute(
            name: "Default",
            url: "{action}",
            defaults: new { controller = "API", action = "Index" }
        );

移动应用发布到 URL https://api.test.com/NewItems,参数是一个 JSON 编码的字典,有一个键 newItems,值是一个字典数组 ([["user": "testUser1", "itemNumber": "123-45678"], ["user": "testUser2", "itemNumber": "456-7890"]])

我在 POST 方法中设置了一个 try/catch 块来捕获任何错误。当方法被发布到时,它会进入 catch 块并告诉我 newItemsDictionary 参数中不存在“newItem”键。参数中确实存在的键是:actioncontroller。操作和控制器键不包含任何值。

为什么会发生这种情况,我应该改变什么来接收正确的数据?

【问题讨论】:

  • 您的 NewItems 参数非常混乱。您需要将 javascript 对象结构与参数匹配,然后您可以在对象上调用 json.stringify 以序列化为 json。

标签: c# asp.net json asp.net-mvc asp.net-mvc-4


【解决方案1】:

发生这种情况是因为请求模型绑定与字典一起使用,因此,如果您期望字典,您可能会处理请求本身。

您应该将字典更改为 ViewModel 或您可以使用的东西。对于 IE:

public class UserItemViewModel 
{
    public string User { get; set; }
    public string ItemNumber { get; set; }
}

然后,您发布 UserItemViewModel 列表。

【讨论】:

  • OP 声明参数为 ([["user": "testUser1", "itemNumber": "123-45678"], ["user": "testUser2", "itemNumber": "456 -7890"]]) 这将是通过 json 传递参数的正确格式。
  • OP 可以这样尝试NewItems(List&lt;UserItemViewModel&gt; newItems),未经测试我无法确定。
  • 我不能使用视图模型。数据不是通过任何类型的 Web 应用程序传入的。它是由移动应用程序发布的。
  • 没关系。您传递给操作的 json 数据将由 Model Binder 解析为 UserItemViewModel。
  • @bkhosh2 将其简单地发布为 UserItemViewModel 数组。 [ {“user”:“testUser1”,“itemNumber”:“123-45678”},{“user”:“testUser2”,“itemNumber”:“456-7890”}]
【解决方案2】:

您为什么需要等待需要以容易出错的方式处理的Dictionary 对象列表。

如果将请求映射到strongly typed 对象会更好。

public class ItemsViewModel 
{
    public string user;
    public string itemNumber;
}

那么您的 Api 方法将如下所示:

[HttpPost]
public void NewItems(List<ItemsViewModel> newItems) 
{
     foreach(var item in newItems){
         item.user... // And so on.
     }
}

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多