8

I'm trying to pass a Dictionary<string,string> object as a parameter to my web api method but if I inspect the log file it always comes through with a count of 0:

Web api method:

[HttpPost]
[ActionName("SendPost")]
public void SendPost([FromBody] Dictionary<string,string> values)
{
    using (var sw = new StreamWriter("F:\\PostTest.txt", true))
    {
        sw.WriteLine("Number of items in the dictionary - " + values.Count);
    }
}

Logic which calls the web api:

public HttpResponseMessage Send(string uri, string value)
{
    HttpResponseMessage responseMessage = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(URI);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var content = new FormUrlEncodedContent
            (
                new Dictionary<string, string> { { "value", value } }
            );

        responseMessage = client.PostAsync(uri, content).Result;
    }
    return responseMessage;
}

1 Answer 1

8

The problem is with the fact that you're saying the content-type is "application/json", yet you pass it as FormUrlEncodedContent. You need to either use StringContent and serialize the content to JSON yourself, or you can use the extention method HttpClientExtensions.PostAsJsonAsync which serializes the content to JSON for you:

public async Task<HttpResponseMessage> SendAsync(string uri, string value)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(URI);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

        return await client.PostAsJsonAsync(uri, content);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I've changed my method to use PostAsJsonAsync but it's still saying the dictionary count in the log file is 0.Should I also change how I'm passing through the content in my example?
@DenisWessels Did you use the code I posted? Or did you modify yours?
Sorry I'm being silly, I read your explanation properly and changed my logic to use PostAsJsonAsync and pass through the dictionary directly without creating FormUrlEncodedContent.Now it's working!
@DenisWessels Great :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.