簡體   English   中英

C#:在HTTP中使用Content-Type標頭發送參數

[英]C#: Sending parameter with Content-Type Header in HTTP

我嘗試使用HTTP client發送HTTP post請求。同時使用StringContent方法設置Content-Type標頭時,出現錯誤:

格式“ application / json; ty = 2”不正確

我的代碼如下:

string result2 = JsonConvert.SerializeObject(values);
 var content = new StringContent(result2, Encoding.UTF8, "application/json; ty=2");
 var response = await client.PostAsync("http://127.0.0.1:8080/~/in-cse/in-name", content);
                    var response_string = await response.Content.ReadAsStringAsync();

但是以我的HTTP Post格式,我必須包括ty=2參數以及application/json 我已經與Postman進行了測試,效果很好。 我如何在這里實現同樣的目標。 我什至還發現您可以采用以下格式將參數添加到內容類型: content := "Content-Type" ":" type "/" subtype *(";" parameter)那么為什么它對我不起作用。 **編輯:**甚至嘗試過此操作:

 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://127.0.0.1:8080/~/in-cse/in-name");
                    request.Content = new StringContent(result2, Encoding.UTF8, "application/json;ty=2");

                    client.SendAsync(request).ContinueWith(resposetask => { Console.WriteLine("response:{0}", resposetask.Result); });

我得到的相同錯誤

您將必須在HttpClient DefaultRequestHeaders中使用TryAddWithoutValidation ,如下所示:

client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;ty=2");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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