Passing dictionary <string, string> parameter in web api
I am trying to pass a Dictionary<string,string> object as a parameter to my web api method, but if I check the log file, it always comes with a score 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); } } The logic that calls the web api is:
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; } +8
Denys wessels
source share1 answer
The problem is that you say the content type is "application / json", but you pass it as FormUrlEncodedContent . You need to either use StringContent , or serialize the content for JSON yourself, or you can use the HttpClientExtensions.PostAsJsonAsync extension HttpClientExtensions.PostAsJsonAsync , which serializes the content for 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); } } +7
Yuval Itzchakov
source share