4

I have a json string that is being passed to a webapi, now the problem is, when I try adding special characters, the recieving object becomes null.

Here's I do it.

string json = JsonConvert.SerializeObject(ojectParams); WebClient client = new WebClient(); client.Headers.Add("content-type", "application/json; charset=utf-8"); client.Headers.Add("AppKey", WebUser.AppKey); client.Headers.Add("AppSecret", WebUser.AppSecret); client.Headers.Add("AccountId", WebUser.AccountId.ToString()); if (!string.IsNullOrEmpty(WebUser.StoreId)) { client.Headers.Add("StoreId", WebUser.StoreId); } var returnedStringObject = client.UploadString(string.Format("{0}/{1}", ConfigurationManager.AppSettings["Api"], endpoint), method, json); 

Here's the json string:

"{\"Firstname\":\"kyv®\",\"Lastname\":\"sab®\"}" 

I have added this one on the header hoping that it will fix the issue. But no luck with that.

charset=utf-8 

On the recieving endpoint, the obj becomes null. But when I removed the special characters, the value is being passed.

[HttpPost] public responseObj Endpoint(requestObj request) 

Any ideas? Thanks!

4
  • possible duplicate of Post values are not set because of special characters in Web API Commented May 20, 2014 at 13:27
  • FYI, this post is using async upload. Mine is not. I want it to stay as it is. Commented May 20, 2014 at 13:37
  • Check for model state validity to see if you have any errors Commented May 20, 2014 at 14:01
  • No errors on model state Commented May 20, 2014 at 15:49

2 Answers 2

3

You need to set the Encoding of the WebClient

client.Encoding = Encoding.UTF8; 
Sign up to request clarification or add additional context in comments.

Comments

1

Please see the code below. Note: I did not use JsonConvert.SerializeObject and used HttpClient instead of WebClient

 public static HttpRequestMessage CreateRequest(string requestUrl, HttpMethod method, String obj) { var request = new HttpRequestMessage { RequestUri = new Uri(requestUrl), Method = method, Content = new StringContent(obj, Encoding.UTF8, "application/json") }; return request; } public static void DoAPI() { var client = new HttpClient(); var obj = "{\"Firstname\":\"kyv®\",\"Lastname\":\"sab®\"}"; var httpRequest = CreateRequest("mywebapiURL", HttpMethod.Post, obj); var response = client.SendAsync(httpRequest).Result; Console.WriteLine(response.Content.ReadAsStringAsync().Result); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.