通过字典< string,string> Web API中的参数 [英] Pass a Dictionary<string,string> parameter in web api

查看:99
本文介绍了通过字典< string,string> 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);
    }
}

这篇关于通过字典&lt; string,string&gt; Web API中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆