用C#中相同名称的参数发送POST请求

本文关键字:参数 POST 请求 | 更新日期: 2023-09-27 18:26:14

我想发送POST请求,其中包含许多同名参数:

FormUrlEncodedContent content = new FormUrlEncodedContent(new [] {
  new KeyValuePair < string, string > ("group_id", "344"),
    new KeyValuePair < string, string > ("group_id", "20"),
    new KeyValuePair < string, string > ("group_id", "456")
});

HttpResponseMessage response = await _httpClient.PostAsync("http://localhost/api", content);

但如果我使用上面的请求,我只得到第一个group_id(具有344 id)的响应。你知道我如何使用FormUrlEncodedContent获得"group_id[]=344&group_id[]=20&group_id[]=456"吗?

用C#中相同名称的参数发送POST请求

老问题,但我花了一些时间才弄清楚,所以答案是:

你应该在你的钥匙上使用括号,如下所示:

FormUrlEncodedContent content = new FormUrlEncodedContent(new [] {
  new KeyValuePair < string, string > ("group_id[]", "344"),
    new KeyValuePair < string, string > ("group_id[]", "20"),
    new KeyValuePair < string, string > ("group_id[]", "456")
});

您正在使用具有相同键的多个键值对。这通常是不允许的。这些键值对将被忽略:new KeyValuePair<string, string>("group_id", "20"), new KeyValuePair<string, string>("group_id", "456")

期望这种输入的API必须更改其设计。