【问题标题】:C#: Sending parameter with Content-Type Header in HTTPC#:在 HTTP 中使用 Content-Type 标头发送参数
【发布时间】:2018-02-15 11:04:48
【问题描述】:

我正在尝试使用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); });

我遇到同样的错误

【问题讨论】:

  • 你能点击这个链接吗? stackoverflow.com/a/10679340/4222487
  • @FaizanRabbani 我已经提到该链接仍然无法正常工作。
  • 你是否得到同样的错误?
  • @FaizanRabbani 编辑中提到的相同错误代码
  • 检查我的答案,让我知道它是否适合您?

标签: c# json http-post httpclient


【解决方案1】:

您必须在 DefaultRequestHeadersHttpClient 中使用 TryAddWithoutValidation,如下所示:

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

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2014-09-13
    相关资源
    最近更新 更多