[英]how to properly perform HTTP Post of a JSON object using C# HttpClient?
I have a very simple C# Http Client console app, which needs to do an HTTP POST of a json object to a WebAPI v2. 我有一个非常简单的C#Http客户端控制台应用程序,它需要对WebAPI v2执行json对象的HTTP POST。 Currently, My app can do the POST using FormUrlEncodedContent: 目前,我的应用程序可以使用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;
}
}
}
}
However, when I try to use JSON in the POST body, I get error 415 - Unsupported media Type: 但是,当我尝试在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);
Doing explicit JSON serialization does not change the outcome for me: 执行显式JSON序列化不会改变我的结果:
string json = JsonConvert.SerializeObject(product);
var response = await client.PostAsJsonAsync("api/products", json);
What is the proper way to handle this, and to be able to POST JSON? 处理这个问题的正确方法是什么,并且能够POST JSON?
When I am posting FormUrlEncodedContent this is the extent of the code I am using 当我发布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);
where _authorizationUrl is an an absolute url. 其中_authorizationUrl是一个绝对的url。
I am not setting any of these properties 我没有设置任何这些属性
client.BaseAddress = new Uri("http://localhost:8888/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
like you are. 像你一样。
If you expect it to send as FormUrlEncodedContent , then MediaTypeWithQualityHeaderValue("application/json") is wrong. 如果您希望它作为FormUrlEncodedContent发送,则MediaTypeWithQualityHeaderValue(“application / json”)是错误的。 This will set the request content-type to json. 这会将请求content-type设置为json。 Use application/x-www-form-urlencoded instead or just do not set MediaTypeWithQualityHeaderValue at all. 使用application / x-www-form-urlencoded或者根本不设置MediaTypeWithQualityHeaderValue。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.