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

时间:2015-09-17 09:51:01

标签: 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);
    }
}

调用网络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;
}

1 个答案:

答案 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);
    }
}