Passing json data to a WebApi with special charact

2019-05-06 04:15发布

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!

2条回答
叼着烟拽天下
2楼-- · 2019-05-06 05:09

You need to set the Encoding of the WebClient

client.Encoding = Encoding.UTF8;
查看更多
够拽才男人
3楼-- · 2019-05-06 05:15

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);
    }
查看更多
登录 后发表回答