簡體   English   中英

HTTP PUT 請求 c# 與 JSON 內容

[英]HTTP PUT request in c# with JSON content

我正在嘗試向我的 API 發出 HTTP PUT 請求,該請求僅接受帶有 JSON 的請求。 我想將字符串轉換為 JSON 並將此 JSON 包含在我的 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);
            }

但是,它 API output 如下:

Unexpected token i in JSON at position 0 at JSON.parse (<anonymous>) at createStrictSyntaxError

在我看來, API 期望 JSON object 具有 id 屬性,而您提供的是普通的 Z0ECD18148D7A287401 字符串。

嘗試構建一個實際的 JSON object 代替:

string word= "{ id: 0 }";

或者更好,例如:

var payload = new { id = 0 };
var jsonPut = JsonConvert.SerializeObject(payload); //JSON 

你的代碼有一個錯誤,你試圖第二次序列化一個字符串,所以你可以這樣做

var jsonPut =  "{ \"id\": 0}";
var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");

或者

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM