WebClient (C#/.net) 中的 POST 数组 [英] POST'ing arrays in WebClient (C#/.net)

查看:46
本文介绍了WebClient (C#/.net) 中的 POST 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .net 应用程序,它有一个 WebRequest,它向 POST 多次添加相同的键,从而使其成为 PHP、Java Servlets 等眼中的数组.我想将其重写为使用 WebClient,但如果我多次使用相同的键调用 WebClient 的 QueryString.Add(),它只会附加新值,生成一个逗号分隔的单个值,而不是一个值数组.

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.

我使用 WebClient 的 UploadFile() 发布我的请求,因为除了这些元数据之外,我还想发布一个文件.

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

如何使用 WebClient 发布值数组而不是单个值(逗号分隔值)?

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

干杯

尼克

推荐答案

PHP 只是使用解析器将多个以数组格式发送的值转换为数组.格式为[].

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

因此,如果您想从 $_GET 接收 PHP 中的数组,请添加以下查询参数:x[key1]x[key2].$_GET['x'] 在 PHP 中将是一个包含 2 项的数组:["x"]=>数组(2){ [key1"]=><随便>[key2"]=><随便>}.

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++;
        }
    }
}

并在代码中:

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

或手动:

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

没有错误检查等.你可以自己做:)

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

这篇关于WebClient (C#/.net) 中的 POST 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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