一种可能性是使用异步上传数据方法允许您在编码数据时指定 UTF-8,因为UploadStringAsync
您使用的方法基本上使用Encoding.Default
将数据写入套接字时对数据进行编码。因此,如果您的系统配置为使用 UTF-8 以外的其他编码,您就会遇到麻烦,因为UploadStringAsync
使用您的系统编码,而在您指定的内容类型标头中charset=utf-8
这可能是矛盾的。
随着UploadDataAsync
方法你可以更明确地表达你的意图:
Animal a = new Animal();
a.Message = "öçşistltl";
string postDataString = JsonConvert.SerializeObject(a);
string URL = "http://localhost/Values/DoSomething";
string postDataString = JsonConvert.SerializeObject(a);
using (WebClient client = new WebClient())
{
client.UploadDataCompleted += client_UploadDataCompleted;
client.Headers["Content-Type"] = "application/json; charset=utf-8";
client.UploadDataAsync(new Uri(URI), "POST", Encoding.UTF8.GetBytes(postDataString));
}
另一种可能性是指定客户端的编码并使用UploadStringAsync
:
Animal a = new Animal();
a.Message = "öçşistltl";
string postDataString = JsonConvert.SerializeObject(a);
string URL = "http://localhost/Values/DoSomething";
string postDataString = JsonConvert.SerializeObject(a);
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.UploadStringCompleted += client_UploadStringCompleted;
client.Headers["Content-Type"] = "application/json; charset=utf-8";
client.UploadStringAsync(new Uri(URI), "POST", postDataString);
}
或者如果您安装Microsoft.AspNet.WebApi.Client客户端上的NuGet包可以直接使用新的HttpClient
类(这是新来的)来使用你的 WebAPI 而不是WebClient
:
Animal a = new Animal();
a.Message = "öçşistltl";
var URI = "http://localhost/Values/DoSomething";
using (var client = new HttpClient())
{
client
.PostAsync<Animal>(URI, a, new JsonMediaTypeFormatter())
.ContinueWith(x => x.Result.Content.ReadAsStringAsync().ContinueWith(y =>
{
Console.WriteLine(y.Result);
}))
.Wait();
}