【问题标题】:Pass a Dictionary<string,string> parameter in web api在 web api 中传递 Dictionary<string,string> 参数
【发布时间】:2015-09-17 09:51:00
【问题描述】:

我正在尝试将 Dictionary&lt;string,string&gt; 对象作为参数传递给我的 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);
    }
}

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

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    问题在于您说内容类型是“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);
        }
    }
    

    【讨论】:

    • 我已经更改了使用 PostAsJsonAsync 的方法,但它仍然说日志文件中的字典计数为 0。我是否还应该更改我在示例中传递内容的方式?
    • @DenisWessels 你使用了我发布的代码吗?还是你修改了你的?
    • 对不起,我很傻,我正确阅读了您的解释并更改了我的逻辑以使用 PostAsJsonAsync 并直接通过字典而不创建 FormUrlEncodedContent。现在它正在工作!
    • @DenisWessels 很棒 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2012-05-13
    相关资源
    最近更新 更多