通过字典< string,string> Web API中的参数 [英] Pass a Dictionary<string,string> parameter in web api
问题描述
我试图将Dictionary<string,string>
对象作为参数传递给我的Web api方法,但是如果我检查日志文件,则总是以0计数:
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:
网络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;
}
推荐答案
问题在于您所说的内容类型为"application/json",但您将其作为FormUrlEncodedContent
传递了.您需要使用StringContent
并将您自己的内容序列化为JSON,或者可以使用扩展方法
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);
}
}
这篇关于通过字典< string,string> Web API中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!