javascript - 使用 vanilla Javascript 将字符串列表发送到 ASP.net api Controller

标签 javascript asp.net json asp.net-core asp.net-web-api

使用普通 Javascript 将字符串列表发送到 ASP.net core api Controller

这听起来可能很简单,但出了点问题,我不确定是什么。我正在尝试将诸如 [ "something", "something else", "Another string"] 之类的字符串列表发送到 ASP.Net Core 中的 api post Controller 。

我的 Controller 看起来像这样

[HttpPost]
        public ActionResult<MyModel> Name([FromBody] List<string> list)
        {

            // Do something... 

            return NoContent();
        }

我的 Javascript 看起来像这样

async function apiCall() {

                const response = await fetch("URL", {
                    method: 'POST',
                    headers: {
                        'Content-type': 'application/json',
                        'X-CSRFToken': csrftoken
                    },
                    body: JSON.stringify({ list: [ "something", "something else", "Another string" ] })
                }}

每当我调用 apiCall() 函数时,它都会将数据发送到 Controller ,但数据 List 始终为空。我如何正确发布这些数据?

最佳答案

改变

body: JSON.stringify({ list: [ "something", "something else", "Another string" ] })

body: JSON.stringify([ "something", "something else", "Another string" ])

而且它有效。我没有发送字符串数组,而是发送一个具有字符串数组作为属性的对象。

关于javascript - 使用 vanilla Javascript 将字符串列表发送到 ASP.net api Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61427149/

相关文章:

javascript - 仅使用 javascript 将多个图像附加到 div

asp.net - System.Net.Mail.SmtpFailedRecipientException : Mailbox unavailable.

asp.net - Web Api 帮助页面来自 1 个以上文件的 XML 注释

c# - 获取 gridview 的页脚行单元格值

javascript - 运行nodejs/expressjs中的多个函数

javascript - 更短的代码而不是对所有组合使用 IF

c# - System.Json 中的错误?

java - 在 Java 中创建 JSON Web token

javascript - JS - 从缓冲区播放音频

java - 将 JSON 转换为 XML,而不将十进制转换为科学记数法