【问题标题】:Send POST request with the same name of parameters in C#在 C# 中发送具有相同参数名称的 POST 请求
【发布时间】:2014-10-12 13:07:18
【问题描述】:

我想发送带有多个同名参数的 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(ID 为 344)的响应。您知道如何使用 FormUrlEncodedContent 获取 "group_id[]=344&group_id[]=20&group_id[]=456" 吗?

【问题讨论】:

  • 您是否尝试过像这样 [344, 20, 456] 将 group_id 作为键和值作为数组传递?
  • 我试过类似:FormUrlEncodedContent content = new FormUrlEncodedContent(new[] { new KeyValuePair&lt;string, string[]&gt;("group_id", new string[] {"344", "20"} ) }); 但是,我得到错误:1. 'System.Net.Http.FormUrlEncodedContent.FormUrlEncodedContent(System.Collections.Generic. IEnumerable>)' 有一些无效参数

标签: c# rest http-post


【解决方案1】:

老问题,但我花了一些时间来解决这个问题,所以这是答案:

你应该像这样在你的键中使用括号:

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")
});

【讨论】:

    【解决方案2】:

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

    需要这种输入的 API 必须改变它的设计。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2022-01-04
      • 2015-12-26
      • 2021-07-27
      • 2014-05-13
      • 2010-12-22
      • 2010-12-12
      相关资源
      最近更新 更多