C# Equivalent of PHP http_build_query


C# Equivalent of PHP http_build_query

我需要使用HttpWebRequest从C#客户端向服务器上的PHP页面传递一些数据。根据文档,预期的数据是一个数组,类似于以下内容:

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

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

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

我该怎么做?http_build_query在生成输出字符串时遵循什么规则?

还有一个非常类似的问题——将PHP数组转换为C#,不幸的是,这并不能解决我的问题。公认的答案推荐了一个固定结构的解决方案,第二个根本不起作用。

好吧,.NET中似乎没有任何内置的东西可以让你做到这一点。但是,如果你想在.NET中重新实现PHP行为,你可以通过查看PHP源代码来实现它,也可以通过阅读http_build_query的PHP文档并在各种输入上测试函数来实现它。

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

/// <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,
                   };
    }
  }
}

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

例如,以下内容:

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

使用NameValueCollection可以做到这一点:

private string ToQueryString(NameValueCollection queryData)
{
    var array = (from key in queryData.AllKeys
        from value in queryData.GetValues(key)
        select string.Format(CultureInfo.InvariantCulture, "{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)))
        .ToArray();
    return "?" + string.Join("&", array);
}