Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultipartFormDataContent does not post StringContent items when the name does not end with []

Tags:

c#

httpclient

Considder the following code:

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

This data is then posted to a Generic Handler which does:

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

If I do this, only names that end in '[]' are posted, but I also need to be able to post names without the '[]'. Any idea why this behaviour occurs and how to solve it?

Note: When using a FormUrlEncodedContent, names without [] do get posted.

like image 275
Nick Kusters BC Avatar asked Jul 05 '26 19:07

Nick Kusters BC


1 Answers

form.Add(new StringContent(Opts.DataType), "\"fieldname\"");
form.Add(new ByteArrayContent(mycontent, 0, mycontent.Length), "\"filename\"", "filename.csv");

Seems unnecessary, but it works.

like image 154
J-DawG Avatar answered Jul 07 '26 08:07

J-DawG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!