Passing json data to a WebApi with special characters results to null

后端 未结 2 1772
夕颜
夕颜 2021-01-13 20:02

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.

相关标签:
2条回答
  • 2021-01-13 20:13

    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);
        }
    
    0 讨论(0)
  • 2021-01-13 20:34

    You need to set the Encoding of the WebClient

    client.Encoding = Encoding.UTF8;
    
    0 讨论(0)
提交回复
热议问题