我正在尝试将Dictionary<string,string>
对象作为参数传递给我的web api方法,但是如果我检查日志文件,它总是会计数为0:
Web api方法:
[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);
}
}
调用网络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;
}
答案 0 :(得分:7)
问题在于您说内容类型是“application / json”,但是您将其作为FormUrlEncodedContent
传递。您需要使用StringContent
并自行将内容序列化为JSON,或者您可以使用将内容序列化为JSON的扩展方法HttpClientExtensions.PostAsJsonAsync
:
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);
}
}