我有一个非常简单的C#Http客户端控制台应用程序,它需要对WebAPI v2执行json对象的HTTP POST。 目前,我的应用可以使用FormUrlEncodedContent进行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);
处理此问题的正确方法是什么,以及能够POST JSON?
答案 0 :(得分:3)
当我发布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是绝对网址。
我没有设置任何这些属性
client.BaseAddress = new Uri("http://localhost:8888/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
像你一样。
答案 1 :(得分:2)
如果您希望将其作为 FormUrlEncodedContent 发送,则MediaTypeWithQualityHeaderValue(&#34; application / json&#34;)是错误的。这会将请求content-type设置为json。请改用application / x-www-form-urlencoded,或者根本不设置MediaTypeWithQualityHeaderValue。