0

I'm sending a dictionary with a call such as the following:

public async Task<string> Test(string val1, string val2)
{
    string res = null;

    using (HttpClient http = new HttpClient())
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();

        dic.Add("value1", val1);
        dic.Add("value2", val2);

        string data = JsonHelper.Serialize<Dictionary<string, string>>(dic);

        using (StringContent content = new StringContent(data, Encoding.UTF8, "application/json"))
        {
            Uri uri = new Uri("http://www.whatever.com/api/test");

            using (HttpResponseMessage response = await http.PostAsync(uri, content))
            {
                res = await response.Content.ReadAsAsync<string>();
            }
        }
    }

    return res;
}

and I see that on the receiving side the dictionary get always deserialized as empty.

[HttpPost]
public IHttpActionResult Test(Dictionary<string, string> req)
{
    return Ok();
}

What am I doing wrong?

If I try to get the body of the request (string body = await Request.Content.ReadAsStringAsync();) and deserialied it manually using a DataContractJsonSerializer I get the expected Dictionary.

whatever
  • 2,492
  • 6
  • 30
  • 42
  • can you tell more about the receiving side of dictionary.this is not clear from your question. – Trilok Kumar Jun 09 '18 at 23:04
  • I'm using owin to create a self-hosted web api 2 interface. Clearly the method I posted is part of a controller class. The method gets correctly called and the correct serialized json is received and I can successfully deserialize it manually, but clearly this is not what I want and expect. – whatever Jun 10 '18 at 08:44
  • To add something more about my discoveries, it seems that the issue lies with using the dictionary. I tried using a List> as suggested by https://stackoverflow.com/a/10585834/5014665 and on the receiving side the collection gets correctly deserialized. – whatever Jun 10 '18 at 08:46
  • 1
    You don't need to do all the serialisation yourself. You could save yourself a lot of work by just doing PostAsAsync(uri, dic); Try that and see if the receiving end deserialises it properly. Also, you might need `[FromBody]` on the parameter of your receiving method. – Craig H Jun 10 '18 at 17:07
  • @CraigH another user had already posted about the FromBody attribute and I replied that the I had already tested the attribute and that it made no difference. As for not doing the serialization manually are you suggesting using `PostAsJsonAsync` ? – whatever Jun 10 '18 at 17:16
  • Sorry, I meant `PostAsJsonAsync(uri, dic)`. It's an extension method that's part of the nuget package Microsoft.AspNet.WebApi.Client – Craig H Jun 11 '18 at 07:11

0 Answers0