由于Web API中的特殊字符,未设置发布值

我正在尝试为我的网络API服务发帖。 重点是发送消息时

{ message: "it is done" } 

工作正常。 但是当我在我的消息中使用像çıöpş这样的特殊字符时,它无法转换我的json以使post对象保持为null。 我能做什么? 这既是当前的文化问题,也可能是其他问题。 我试图将我的post参数发送为带有编码HttpUtility类的HtmlEncoded样式,但它也不起作用。

 public class Animal{ public string Message {get;set;} } 

Web API方法

 public void DoSomething(Animal a){ } 

客户

 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); 

最好的祝福,

凯末尔

一种可能性是使用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(URI, a, new JsonMediaTypeFormatter()) .ContinueWith(x => x.Result.Content.ReadAsStringAsync().ContinueWith(y => { Console.WriteLine(y.Result); })) .Wait(); }