我将POST请求发送到API。这是我的代码:
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var postData = JsonConvert.SerializeObject(claim);
var response = await client.PostAsync($"api/Claims/Save", new StringContent(postData, Encoding.UTF8, "application/json"));
我序列化对象并发送,但是在API中,我的代码是这样的:
[System.Web.Http.HttpPost]
public IHttpActionResult Save(string user , string description , string data)
如果是HTTP GET,我知道您在url上添加了参数,但是我不知道如何使用HTTP POST进行设置。问题是我无法更改API请求。
声明对象包含字符串user,字符串描述,字符串数据
编辑
我无法更改API,不是我的!
答案 0 :(得分:0)
如果有人遇到相同情况:
首先,您需要添加Content-Type:application/x-www-form-urlencoded
第二,您需要根据您的值创建一个字典,例如:
var dictionary = new Dictionary<string, string>();
dictionary.Add("values", "Doctor");
dictionary.Add("name", "John");
dictionary.Add("surname", "Doe");
dictionary.Add("Year", "1993");
第三,您需要像这样对内容进行编码:
var content = new FormUrlEncodedContent(dictionary);
最后发送请求:
var response = await client.PostAsync($"api/Claims/Save", content);