Pass a Dictionary parameter in web api

后端 未结 1 1830
天涯浪人
天涯浪人 2021-01-12 04:16

I\'m trying to pass a Dictionary object as a parameter to my web api method but if I inspect the log file it always comes through with a co

相关标签:
1条回答
  • 2021-01-12 04:24

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题