POST'ing arrays in WebClient (C#/.net)

橙三吉。 提交于 2019-12-17 16:47:07

问题


I've got a .net application that has a WebRequest that to a POST adds multiple times the same key, thus making it an array in the eyes of PHP, Java Servlets etc. I wanted to rewrite this to using WebClient, but if I call WebClient's QueryString.Add() with the same key multiple times, it just appends the new values, making a comma-separated single value instead of an array of values.

I post my request using WebClient's UploadFile() because in addition to these metadata I want a file posted.

How can I use WebClient to post an array of values instead of a single value (of comma-separated values)?

Cheers

Nik


回答1:


PHP simply uses a parser to convert multiple values sent with array format to an array. The format is <arrayName>[<key>].

So if you want to receive an array in PHP from $_GET add these query parameters: x[key1] and x[key2]. $_GET['x'] in PHP will be an array with 2 items: ["x"]=> array(2) { ["key1"]=> <whatever> ["key2"]=> <whatever> }.

Edit - you can try this extension method:

public static class WebClientExtension
{
    public static void AddArray(this WebClient webClient, string key, params string[] values)
    {
        int index = webClient.QueryString.Count;

        foreach (string value in values)
        {
            webClient.QueryString.Add(key + "[" + index + "]", value);
            index++;
        }
    }
}

and in code:

webClient.AddArray("x", "1", "2", "3");
webClient.AddArray("x", "4");

or manually:

webClient.QueryString.Add("x[key1]", "4");
webClient.QueryString.Add("x[key2]", "1");

There is no error checking, etc. You can do it yourself :)



来源:https://stackoverflow.com/questions/3942427/posting-arrays-in-webclient-c-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!