带有其他参数的 C# HttpClient Post 字符串数组

标签 c# post httpclient paramarray

我正在编写一个 C# api 客户端,对于大多数发布请求,我使用 FormUrlEncodedContent 来发布数据。

List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();

keyValues.Add(new KeyValuePair<string, string>("email", email));
keyValues.Add(new KeyValuePair<string, string>("password", password));

var content = new FormUrlEncodedContent(keyValues);

但现在我需要发布一个字符串数组作为一个参数。像下面这样的东西。

string[] arr2 = { "dir1", "dir2"};

如何使用 C# HttpClient 发送此数组以及其他字符串参数。

最佳答案

我遇到了同样的问题,我必须将一些常规字符串参数和字符串数组添加到 Http POST 请求正文中。

为此,您必须执行类似于以下示例的操作(假设您要添加的数组是一个名为 dirArray 的字符串数组):

//Create List of KeyValuePairs
List<KeyValuePair<string, string>> bodyProperties = new List<KeyValuePair<string, string>>();

//Add 'single' parameters
bodyProperties.Add(new KeyValuePair<string, string>("email", email));
bodyProperties.Add(new KeyValuePair<string, string>("password", password));

//Loop over String array and add all instances to our bodyPoperties
foreach (var dir in dirArray)
{
    bodyProperties.Add(new KeyValuePair<string, string>("dirs[]", dir));
}

//convert your bodyProperties to an object of FormUrlEncodedContent
var dataContent = new FormUrlEncodedContent(bodyProperties.ToArray());

关于带有其他参数的 C# HttpClient Post 字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29791466/

相关文章:

java - Twitter4j HTTPClient 代理服务器和 Java

c# - .NET 核心 : HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?

c# - System.Private.ServiceModel 的问题

c# - RFID RC522 Raspberry PI 2 Windows 物联网

javascript - 带有 JS 操作的 PHP SQL 表单 - 仅在单个 div 而不是所有 div 中显示结果

java - 如何在java中发送带有post参数的简单http post请求

c# - 如何在分隔符上拆分字符串,并将分隔符作为结果数组中的元素保留?

c# - C#WinForms应用-调试错误-长度不能小于零。参数名称: Length

web-services - 将 asp.net 2.0 webmethod 设置为 GET 方法

java - HttpClient:如何从现有连接获取底层套接字?