使用POST C#发送的字典为空

时间:2016-10-30 03:11:47

标签: c# django dictionary post

我正在尝试使用C#中的POST将字典发送到django服务器。 服务器接收请求并使用200消息进行确认,但是它接收到空的多值字典。

这是发送POST请求的客户端。

public class Hello1
{
    public static void Main()
    {
        Console.WriteLine("Request Initiating");

        using (var wb = new WebClient())
        {
            var data = new NameValueCollection();


            data["key1"] = "test";
            data["key2"] = "TEST2";
            data["key3"] = "NA";

            string url = "http://10.34.150.153:8000/key_detect/detect/";
            var response = wb.UploadValues(url, "POST", data);
            string result = System.Text.Encoding.UTF8.GetString(response);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

看这篇文章: POSTing JSON to URL via WebClient in C#

在上传之前,您需要将数据序列化为JSON。

var data = new NameValueCollection();
data["key1"] = "test";
data["key2"] = "TEST2";
data["key3"] = "NA";

using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(data);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
  

先决条件:Json.NET library