voj*_*jta 7 php c# arrays post http
我需要使用C#客户端将一些数据传递到服务器上的PHP页面HttpWebRequest.根据文档的预期数据是一个数组数组,如下所示:
$postData = array(
'label1' => 'myLabel',
'label2' => array(
'label2_1' => 3
'label2_2' => array(
'label2_2_1' => 3
)
)
);
Run Code Online (Sandbox Code Playgroud)
上面的结构只是一个例子.它可能非常复杂,结构本身也不是一成不变的.
在PHP中有一个名为的函数http_build_query,它将这些PHP嵌套数组序列化为一个简单的字符串,该字符串可以作为HTTP POST请求的数据发送.问题是我需要从我的C#应用程序调用这个PHP页面.我想将这些嵌套数组表示为嵌套数据Dictionary<string, object>或匿名类型.
我怎样才能做到这一点?http_build_query生成输出字符串后会遵循什么规则?
有一个非常类似的问题将PHP数组转换为C#,遗憾的是这并没有解决我的问题.接受的答案建议采用固定结构的解决方案,第二种方法根本不起作用.
Fri*_*Guy 15
好吧,似乎没有任何内置的.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,
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
代码非常简单,但它接受字典,数组或对象.如果它是顶级对象,则序列化属性.如果它是一个数组,则使用适当的数组索引序列化每个元素.如果它是字典,则键/值被序列化.包含其他数组或字典的数组和字典值被展平,类似于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" },
}
}
);
Run Code Online (Sandbox Code Playgroud)
产生:
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
Run Code Online (Sandbox Code Playgroud)
这是:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3274 次 |
| 最近记录: |