[英]HTTP PUT request in c# with JSON content
I am trying to make an HTTP PUT request to my API that only accepts request with JSONs.我正在尝试向我的 API 发出 HTTP PUT 请求,该请求仅接受带有 JSON 的请求。 I want to convert string to JSON and include this JSON in my PUT request.我想将字符串转换为 JSON 并将此 JSON 包含在我的 PUT 请求中。 This is my code:这是我的代码:
//PUT //放
string word= "id: 0";
var requestURI3 = new HttpRequestMessage();
string url = "https://...";
Debug.WriteLine(url);
requestURI3.RequestUri = new Uri(url);
requestURI3.Method = HttpMethod.Put;
requestURI3.Headers.Add("Accept", "application/json");
var jsonPut = JsonConvert.SerializeObject(word); //JSON
var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");
var client3 = new HttpClient();
HttpResponseMessage responseURI3 = await client3.PutAsync(url,contentJsonPut);
if (responseURI3.StatusCode == HttpStatusCode.OK)
{
Debug.WriteLine("Put made correctly");
}
else
{
Debug.WriteLine("Error in put");
Debug.WriteLine(responseURI3.StatusCode);
}
However, it API output is the following:但是,它 API output 如下:
Unexpected token i in JSON at position 0 at JSON.parse (<anonymous>) at createStrictSyntaxError
Seems to me the API expects a JSON object with id property, and you offer it a plain JSON string.在我看来, API 期望 JSON object 具有 id 属性,而您提供的是普通的 Z0ECD18148D7A287401 字符串。
Try constructing an actual JSON object instead:尝试构建一个实际的 JSON object 代替:
string word= "{ id: 0 }";
Or better, something like:或者更好,例如:
var payload = new { id = 0 };
var jsonPut = JsonConvert.SerializeObject(payload); //JSON
your code has a bug, you are trying to serialize a string for the second time, so you can do this你的代码有一个错误,你试图第二次序列化一个字符串,所以你可以这样做
var jsonPut = "{ \"id\": 0}";
var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");
or或者
var id = new { id = 0 };
var jsonPut = JsonConvert.SerializeObject(id);
var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.