【发布时间】:2018-01-07 02:53:42
【问题描述】:
我有一个在 c# 中运行的 Web API 服务器。 httpget 方法完美运行,但我对 Web Api 太陌生,无法让帖子正常工作,而且我所做的搜索有点无结果。
这是我在 ApiController 中的 HttpPost
[HttpPost]
public bool UploadLogs(UploadLogsIn logs)
{
return true;
}
这是模型
public class UploadLogsIn
{
public byte[] logData { get; set; }
public int aLogs { get; set; }
}
在 C++ 应用程序中,我尝试将数据发布到此方法。我正在使用 Curl 来发帖
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.56.109:9615/api/WebApiService/UploadLogs");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, R"({"UploadLogsIn": [{"aLogs: 10}]})");
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20);
curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
当我调试 Web Api 时,该方法被命中,但参数不包含任何数据。
更新 使用wireshark,这是发送的信息
POST /api/WebApiService/UploadLogs HTTP/1.1
Host: 192.168.56.109:9615
Accept: */*
Content-Length: 32
Content-Type: application/x-www-form-urlencoded
Form item: "{"UploadLogsIn": [{"aLogs: 10}]}" = ""
结束更新
如果我添加标题
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
那么我的参数为空。
为此的 Wireshark 转储是
POST /api/WebApiService/UploadLogs HTTP/1.1
Host: 192.168.56.109:9615
Accept: application/json
Content-Type: application/json
charsets: utf-8
Content-Length: 32
Line-based text data: application/json
{"UploadLogsIn": [{"aLogs: 10}]}
我确定我做错了一些愚蠢的事情。任何帮助将不胜感激
【问题讨论】:
-
发送的数据不是格式良好的 JSON 数据。查看您是如何构建 JSON 对象的。类与发送的 json 不匹配
-
我已将字符串更改为 `curl_easy_setopt(curl, CURLOPT_POSTFIELDS, R"({"UploadLogsIn": [{"aLogs": 10}]})"); JSON中还有什么问题吗?在这个阶段结果保持不变
标签: c# curl asp.net-web-api