在web api中传递Dictionary 参数

我正在尝试将Dictionary对象作为参数传递给我的web api方法,但如果我检查日志文件,它总是会计数为0:

Web api方法:

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

调用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 { { "value", value } } ); responseMessage = client.PostAsync(uri, content).Result; } return responseMessage; } 

问题在于您说内容类型是“application / json”,但是您将其作为FormUrlEncodedContent传递。 您需要使用StringContent并自行将内容序列化为JSON,或者您可以使用扩展方法HttpClientExtensions.PostAsJsonAsync将内容序列化为JSON:

 public async Task 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); } }