如何正确使用C#HttpClient执行JSON对象的HTTP Post?

问题描述:

我有一个非常简单的C#Http Client控制台应用程序,它需要对WebAPI v2执行json对象的HTTP POST。 目前,我的应用程序可以做POST使用FormUrlEncodedContent:如何正确使用C#HttpClient执行JSON对象的HTTP Post?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using Newtonsoft.Json; 
using System.Net.Http.Formatting; 


namespace Client1 
{ 
    class Program 
    { 
     class Product 
     { 
      public string Name { get; set; } 
      public double Price { get; set; } 
      public string Category { get; set; } 
     } 
     static void Main(string[] args) 
     { 
      RunAsync().Wait(); 
     } 
     static async Task RunAsync() 
     { 
      using (var client = new HttpClient()) 
      { 
       client.BaseAddress = new Uri("http://localhost:8888/"); 
       client.DefaultRequestHeaders.Accept.Clear(); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

       var content = new FormUrlEncodedContent(new[] 
         { 
          new KeyValuePair<string, string>("Category", "value-1"), 
          new KeyValuePair<string, string>("Name", "value-2")       
         }); 

       var result = client.PostAsync("Incident", content).Result;  
       var r = result;  
      } 
     } 
    } 
} 

然而,当我尝试在POST体使用JSON,我得到错误415 - 不支持的媒体类型:

class Product 
{ 
    public string Name { get; set; } 
    public double Price { get; set; } 
    public string Category { get; set; } 
} 

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; 
var response = await client.PostAsJsonAsync("api/products", gizmo); 

做明确JSON序列化不会改变我的结果:

string json = JsonConvert.SerializeObject(product); 
var response = await client.PostAsJsonAsync("api/products", json); 

什么是处理这个问题,并能够发布JSON的正确方法?

+1

你是否拥有服务器实现? '415 - Unsupported media Type'是一个服务器端错误,它说它不支持JSON,因此与您的客户端代码无关。 – Jacob

+0

是的,我的服务器端是一个OData控制器:[HttpPost] public void Post([FromBody] Product value) { var req = Request; var p = value; } –

+1

是的,但是您的服务器项目配置为接受并返回JSON?看看为你的请求添加头文件,以表示你也发送了JSON。 – krillgar

如果您希望它发送为FormUrlEncodedContent,那么MediaTypeWithQualityHeaderValue(“application/json”)是错误的。这会将请求内容类型设置为json。改用application/x-www-form-urlencoded或者根本不要设置MediaTypeWithQualityHeaderValue。

当我张贴FormUrlEncodedContent这是我使用

 HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string> 
     { 
      {"grant_type", "password"}, 
      {"client_id", _clientId}, 
      {"client_secret", _clientSecret}, 
      {"username", _userName}, 
      {"password", _password} 
     } 
      ); 

      var message = 
       await httpClient.PostAsync(_authorizationUrl, content); 

其中_authorizationUrl是一个绝对URL代码的程度。

像你我没有设置任何这些属性

  client.BaseAddress = new Uri("http://localhost:8888/"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

的。

+0

没错。这就是我在下面的答案中所说的。但不知道为什么有人投了票。 – Developer

+0

谁知道。我会投你一票。 – Fran

+0

感谢队友。干杯... – Developer