【问题标题】:MultipartFormDataContent does not post StringContent items when the name does not end with []当名称不以 [] 结尾时,MultipartFormDataContent 不会发布 StringContent 项
【发布时间】:2012-10-29 15:34:31
【问题描述】:

考虑以下代码:

  MultipartFormDataContent MPFD = new MultipartFormDataContent();
  MPFD.Add(new StringContent(0.ToString()), "doesNotWork");
  MPFD.Add(new StringContent(0.ToString()), "works[]");
  HttpClient apiClient = new HttpClient();
  var Result = apiClient.PostAsync(testurl, MPFD).Result;
  Console.WriteLine("Response: " + Result.Content.ReadAsStringAsync().Result);

然后将此数据发布到通用处理程序,该处理程序执行以下操作:

context.Response.ContentType = "text/plain";
foreach (string key in context.Request.Form.AllKeys) {
  context.Response.Write(key + ": " + context.Request.Form[key] + Environment.NewLine);
}

如果我这样做,只会发布以“[]”结尾的名称,但我还需要能够发布不带“[]”的名称。知道为什么会出现这种行为以及如何解决吗?

注意:当使用 FormUrlEncodedContent 时,不带 [] 的名称会被发布。

【问题讨论】:

  • “如果我这样做,只会发布以 '[]' 结尾的名称” - 您是否对此进行了验证,例如使用 Fiddler

标签: c# httpclient


【解决方案1】:
form.Add(new StringContent(Opts.DataType), "\"fieldname\"");
form.Add(new ByteArrayContent(mycontent, 0, mycontent.Length), "\"filename\"", "filename.csv");

似乎没有必要,但确实有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 2021-07-19
    • 2013-02-05
    • 1970-01-01
    相关资源
    最近更新 更多