One possibility is to use the UploadDataAsync method which allows you to specify UTF-8 when encoding the data because the UploadStringAsync
method that you are using basically uses Encoding.Default
to encode the data when writing it to the socket. So if your system is configured to use some other encoding than UTF-8 you get into trouble because UploadStringAsync
uses your system encoding whereas in your content type header you have specified charset=utf-8
which could be conflicting.
With the UploadDataAsync
method you could be more explicit in your intents:
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));
}
Another possibility is to specify the encoding of the client and use 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);
}
Or if you install the Microsoft.AspNet.WebApi.Client
NuGet package on the client you could directly use the new HttpClient
class (which is the new kid on the block) to consume your WebAPI instead of 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();
}