在web api中传递Dictionary <string,string>参数

Den*_*els 8 c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api

我正在尝试将一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

调用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<string, string> { { "value", value } }
            );

        responseMessage = client.PostAsync(uri, content).Result;
    }
    return responseMessage;
}
Run Code Online (Sandbox Code Playgroud)

Yuv*_*kov 7

问题在于你说内容类型是"application/json",但是你把它传递给了FormUrlEncodedContent.您需要自己使用StringContent内容并将内容序列化为JSON,或者您可以使用HttpClientExtensions.PostAsJsonAsync将内容序列化为JSON 的扩展方法:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)