将空数组发送到 webapi

Posted

技术标签:

【中文标题】将空数组发送到 webapi【英文标题】:Sending empty array to webapi 【发布时间】:2016-10-07 21:48:30 【问题描述】:

我想将一个空的 javascript 数组 [] 发布到 webAPI 并让它创建一个空的整数列表。我也想要它,所以如果我将 javascript null 发布到 webAPI,它会将 null 分配给整数列表。

JS:

var intArray = [];
$.ajax(
    type: 'POST',
    url: '/api/ListOfInts',
    data: '' : intArray,
    dataType: 'json'
);

c#webapi

[HttpPost]
public void ListOfInts([FromBody]List<int> input)

问题 1) Jquery 拒绝发送数据'' : [] 作为后有效载荷。只要我在数组中添加一些东西,它就会起作用,例如'' : [1,2,3]

问题 2) Passing empty js array to controller gives null 根据我读到的内容,即使我确实让它发布了一个空数组,它也会将列表初始化为空。讨论的解决方案有它,因此列表始终初始化为空,但我不希望这样。我希望它在某些情况下为空(当向其发送 null/undefined 时),当发送 [] 时,它应该初始化为空。

编辑:请参阅https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1,了解我为什么使用'' : []

【问题讨论】:

您是否尝试仅发送数据:intArray ? 是的,它根本不起作用。 WebAPI 不知道如何处理它 在 WebApi 中,区分请求中的 null 和 empty 可能很困难。如果您正在使用它们以某种方式在您的应用程序中设置某种“状态”,我会重新考虑您是如何做到的。可能会发送某种标志或其他可以正确初始化服务器上​​的列表的东西。 【参考方案1】:

使用JSON.stringify(intArray)contentType: 'application/json' 对我有用:

$.ajax(
     url: "/api/values",
     method: "POST",
     contentType: 'application/json',
     data: JSON.stringify([])
);

$.ajax(
     url: "/api/values",
     method: "POST",
     contentType: 'application/json',
     data: null
);

$.ajax(
      url: "/api/values",
      method: "POST",
      contentType: 'application/json',
      data: JSON.stringify([1, 2, 3])
);

【讨论】:

【参考方案2】:
data: '' : intArray,

JSON 中不允许使用空白键名。

只需发送数组本身。

data: intArray,

【讨论】:

这是 webAPI 在发送 valuetype 时需要的 根据this question and answer,允许空键。【参考方案3】:

1. 使用 JSON.stringify() 将 javascript 对象转换为 JSON 字符串。

2. 使用 contentType: 'application/json' 因为它是 JSON 的正确 MIME 媒体类型。 What is the correct JSON content type?

3 dataType 不是必需的

数据:JSON.stringify(intArray), contentType:'应用程序/json'

【讨论】:

以上是关于将空数组发送到 webapi的主要内容,如果未能解决你的问题,请参考以下文章

如何在不将空值发送到输出数组的情况下拆分字符串

如何将带有字节数组的 json 发送到 web api / postman

将空参数从 Ajax 发送到控制器

剑道网格发布和删除将空值发送到控制器

angular js使用post方法将空数据发送到php

地理服务器将空矢量图块发送到 Openlayers