C# 等效于 PHP http_build_query

标签 c# php arrays http post

我需要使用 HttpWebRequest 将一些数据从我的 C# 客户端传递到服务器上的 PHP 页面.根据文档的预期数据是一个数组数组,如下所示:

$postData = array(
    'label1' => 'myLabel',
    'label2' => array(
        'label2_1' => 3
        'label2_2' => array(
            'label2_2_1' => 3
        )
    )
);

上面的结构只是一个例子。它可能非常复杂,并且结构本身不是恒定的。

在 PHP 中有一个名为 http_build_query 的函数它将这些 PHP 嵌套数组序列化为一个简单的字符串,可以作为 HTTP POST 请求的数据发送。问题是我需要从我的 C# 应用程序调用此 PHP 页面。我想将这些嵌套数组表示为嵌套 Dictionary<string, object> s,或匿名类型。

我该怎么做? http_build_query有什么规则遵循以产生其输出字符串?

有一个非常相似的问题Converting PHP array of arrays to C# ,不幸的是,这并没有解决我的问题。接受的答案推荐了一个固定结构的解决方案,第二个根本不起作用。

最佳答案

好吧,.NET 中似乎没有任何内置功能可让您执行此操作。但是,如果您想在 .NET 中重新实现 PHP 行为,您可以通过查看 PHP 源代码来白盒实现它,或者通过阅读 PHP documentation of http_build_query 来黑盒实现它。并在各种输入上测试该功能。

我采用了黑盒方法并创建了以下类:

/// <summary>
///  Helps up build a query string by converting an object into a set of named-values and making a
///  query string out of it.
/// </summary>
public class QueryStringBuilder
{
  private readonly List<KeyValuePair<string, object>> _keyValuePairs
    = new List<KeyValuePair<string, object>>();

  /// <summary> Builds the query string from the given instance. </summary>
  public static string BuildQueryString(object queryData, string argSeperator = "&")
  {
    var encoder = new QueryStringBuilder();
    encoder.AddEntry(null, queryData, allowObjects: true);

    return encoder.GetUriString(argSeperator);
  }

  /// <summary>
  ///  Convert the key-value pairs that we've collected into an actual query string.
  /// </summary>
  private string GetUriString(string argSeperator)
  {
    return String.Join(argSeperator,
                       _keyValuePairs.Select(kvp =>
                                             {
                                               var key = Uri.EscapeDataString(kvp.Key);
                                               var value = Uri.EscapeDataString(kvp.Value.ToString());
                                               return $"{key}={value}";
                                             }));
  }

  /// <summary> Adds a single entry to the collection. </summary>
  /// <param name="prefix"> The prefix to use when generating the key of the entry. Can be null. </param>
  /// <param name="instance"> The instance to add.
  ///  
  ///  - If the instance is a dictionary, the entries determine the key and values.
  ///  - If the instance is a collection, the keys will be the index of the entries, and the value
  ///  will be each item in the collection.
  ///  - If allowObjects is true, then the object's properties' names will be the keys, and the
  ///  values of the properties will be the values.
  ///  - Otherwise the instance is added with the given prefix to the collection of items. </param>
  /// <param name="allowObjects"> true to add the properties of the given instance (if the object is
  ///  not a collection or dictionary), false to add the object as a key-value pair. </param>
  private void AddEntry(string prefix, object instance, bool allowObjects)
  {
    var dictionary = instance as IDictionary;
    var collection = instance as ICollection;

    if (dictionary != null)
    {
      Add(prefix, GetDictionaryAdapter(dictionary));
    }
    else if (collection != null)
    {
      Add(prefix, GetArrayAdapter(collection));
    }
    else if (allowObjects)
    {
      Add(prefix, GetObjectAdapter(instance));
    }
    else
    {
      _keyValuePairs.Add(new KeyValuePair<string, object>(prefix, instance));
    }
  }

  /// <summary> Adds the given collection of entries. </summary>
  private void Add(string prefix, IEnumerable<Entry> datas)
  {
    foreach (var item in datas)
    {
      var newPrefix = String.IsNullOrEmpty(prefix)
        ? item.Key
        : $"{prefix}[{item.Key}]";

      AddEntry(newPrefix, item.Value, allowObjects: false);
    }
  }

  private struct Entry
  {
    public string Key;
    public object Value;
  }

  /// <summary>
  ///  Returns a collection of entries that represent the properties on the object.
  /// </summary>
  private IEnumerable<Entry> GetObjectAdapter(object data)
  {
    var properties = data.GetType().GetProperties();

    foreach (var property in properties)
    {
      yield return new Entry()
                   {
                     Key = property.Name,
                     Value = property.GetValue(data)
                   };
    }
  }

  /// <summary>
  ///  Returns a collection of entries that represent items in the collection.
  /// </summary>
  private IEnumerable<Entry> GetArrayAdapter(ICollection collection)
  {
    int i = 0;
    foreach (var item in collection)
    {
      yield return new Entry()
                   {
                     Key = i.ToString(),
                     Value = item,
                   };
      i++;
    }
  }

  /// <summary>
  ///  Returns a collection of entries that represent items in the dictionary.
  /// </summary>
  private IEnumerable<Entry> GetDictionaryAdapter(IDictionary collection)
  {
    foreach (DictionaryEntry item in collection)
    {
      yield return new Entry()
                   {
                     Key = item.Key.ToString(),
                     Value = item.Value,
                   };
    }
  }
}

该代码非常不言自明,但它接受字典、数组或对象。如果它是顶级对象,它会序列化属性。如果它是一个数组,则每个元素都使用适当的数组索引进行序列化。如果它是一个字典,则键/值被序列化。包含其他数组或字典的数组和字典值被展平,类似于 PHP 的行为。

例如,以下内容:

QueryStringBuilder.BuildQueryString(new
       {
         Age = 19,
         Name = "John&Doe",
         Values = new object[]
                  {
                    1,
                    2,
                    new Dictionary<string, string>()
                    {
                      { "key1", "value1" },
                      { "key2", "value2" },
                    }
                  },
       });

// 0=1&1=2&2%5B0%5D=one&2%5B1%5D=two&2%5B2%5D=three&3%5Bkey1%5D=value1&3%5Bkey2%5D=value2
QueryStringBuilder.BuildQueryString(new object[]
       {
         1,
         2,
         new object[] { "one", "two", "three" },
         new Dictionary<string, string>()
         {
           { "key1", "value1" },
           { "key2", "value2" },
         }
       }
  );

生成:

Age=19&Name=John%26Doe&Values%5B0%5D=1&Values%5B1%5D=2&Values%5B2%5D%5Bkey1%5D=value1&Values%5B2%5D%5Bkey2%5D=value2

即:

Age=19&Name=John%26Doe&Values[0]=1&Values[1]=2&Values[2][key1]=value1&Values[2][key2]=value2
Age=19
Name=John&Doe
Values[0]=1
Values[1]=2
Values[2][key1]=value1
Values[2][key2]=value2

关于C# 等效于 PHP http_build_query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34043266/

相关文章:

c# - 启用 WCF 服务以与 JSON 一起使用

php - 如何将一个 wordpress 站点的两个版本?

javascript - 根据计算定义 css 元素

javascript - 将文件名和文件类型放在一个数组中

c# - 在 P/Invoke 中编码字符串时,Mono 使用什么编码?

c# - C# 的行为在 VS2008 调试器中获取类的成员

C#多线程-同步设置点

php - 如何在PHP中引用静态常量成员变量

java - 并行对两个数组的每个元素求和

arrays - 在数组中搜索一个值 [swift]