我正在为第三方API编写一个C#客户端(我正在使用RestSharp nuget包)。他们的文档包含我必须翻译成 C# 的 PHP 示例。他们的大多数示例都非常简单,我已经能够将它们转换为 C#,但我正在努力使用其中一个,因为它接受数组数组。以下是他们文档中的示例:
$params = array (
'user_key' => 'X',
'client_id'=> 'X,
'label' => array(
array(
'language' => 'en_US',
'name' => 'English label',
),
array(
'language' => 'fr_CA',
'name' => 'French label',
),
),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.3rdparty.com/xxx/yyy');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apikey: YOURAPIKEY'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
这是我到目前为止所拥有的:
var labels = new Dictionary<string, string>()
{
{ "en_US", "English Label" },
{ "fr_CA", "French Label" }
};
var request = new RestRequest("/xxx/yyy", Method.POST) { RequestFormat = DataFormat.Json };
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
request.AddParameter("label", ???);
var client = new RestSharp.RestClient("https://api.3rdparty.com")
{
Timeout = timeout,
UserAgent = "My .NET REST Client"
};
var response = client.Execute(request);
有谁知道如何将"标签"字典转换为等同于 PHP http_build_query的格式?
http_build_query($params)
生成如下所示的输出:
user_key=X&client_id=X&label%5B0%5D%5Blanguage%5D=en_US&label%5B0%5D%5Bname%5D=English+label&label%5B1%5D%5Blanguage%5D=fr_CA&label%5B1%5D%5Bname%5D=French+label
解码后,看起来像:
user_key=X&client_id=X&label[0][language]=en_US&label[0][name]=English label&label[1][language]=fr_CA&label[1][name]=French label
因此,您应该能够执行以下操作:
var request = new RestRequest("/xxx/yyy", Method.POST);
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
foreach (var item in labels.Select((pair, i) => new { index = i, language = pair.Key, name = pair.Value }))
{
request.AddParameter(string.Format("label[{0}][language]", item.index), item.language);
request.AddParameter(string.Format("label[{0}][name]", item.index), item.name);
}
请注意,从实验中,我注意到 RestSharp 将空间编码为 %20
而不是+
。 希望不是问题。
您可以使用 HttpBuildQuery,它是该 PHP 函数的镜面实现。