Mail values ​​not set due to special characters in the Web API

I am trying to make a post in my api web service. The fact is that when sending a message like

{ message: "it is done" }

works fine. However, when I use special characters such as çıöpş in my post, it cannot convert my json so that the post object remains null. What can I do? This is either a current cultural issue or something else. I tried sending my post parameter as an HtmlEncoded style with the HttpUtility encoding class, but it didn't work either.

public class Animal{

  public string Message {get;set;}
}

Web api method

public void DoSomething(Animal a){

}

Client

Animal a = new Animal();
a.Message = "öçşistltl";
string postDataString = JsonConvert.SerializeObject(a);        
string URL = "http://localhost/Values/DoSomething";
WebClient client = new WebClient();

client.UploadStringCompleted += client_UploadStringCompleted;
client.Headers["Content-Type"] = "application/json;charset=utf-8";
client.UploadStringAsync(new Uri(URL), "POST",postDataString);

Yours faithfully,

Kemal

+2
source share
1 answer

UploadDataAsync, 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();
}
+6

Source: https://habr.com/ru/post/1541274/


All Articles