简体   繁体   English

C#:在HTTP中使用Content-Type标头发送参数

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

I am trying to send the HTTP post request using HTTP client .while setting my Content-Type header with StringContent method, I am getting the error: 我尝试使用HTTP client发送HTTP post请求。同时使用StringContent方法设置Content-Type标头时,出现错误:

the format "application/json;ty=2 "is incorrect 格式“ application / json; ty = 2”不正确

My code is as follows: 我的代码如下:

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();

But in my HTTP Post format I have to include ty=2 parameter along with application/json . 但是以我的HTTP Post格式,我必须包括ty=2参数以及application/json I have tested this with Postman and it worked perfectly. 我已经与Postman进行了测试,效果很好。 How can I achieve the same thing here. 我如何在这里实现同样的目标。 I also even found you can add parameter to content type in the following format: content := "Content-Type" ":" type "/" subtype *(";" parameter) then why is it not working for me. 我什至还发现您可以采用以下格式将参数添加到内容类型: content := "Content-Type" ":" type "/" subtype *(";" parameter)那么为什么它对我不起作用。 **EDIT:**even tried this: **编辑:**甚至尝试过此操作:

 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); });

same error i am getting 我得到的相同错误

您将必须在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