I am trying to post multipart data using System.Net.Http.HttpClient but when I am instanciating my content I am getting this exception:
A first chance exception of type 'System.ArgumentException' occurred in System.Net.Http.DLL
An exception of type 'System.ArgumentException' occurred in System.Net.Http.DLL and wasn't handled before a managed/native boundary
e: System.ArgumentException: The format of value '---###---' is invalid.
Parameter name: boundary
at System.Net.Http.MultipartContent.ValidateBoundary(String boundary)
at System.Net.Http.MultipartContent..ctor(String subtype, String boundary)
at System.Net.Http.MultipartFormDataContent..ctor(String boundary)
at RestClientUploadFoto.MultipartStackOverflow.<postMultipart>d__2.MoveNext()
here is the method in where I am getting the exception:
public async Task postMultipart()
{
var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
// boundary
String boundary = "---###---"; // should never occur in your data
// This is the postdata
MultipartFormDataContent content = new MultipartFormDataContent(boundary);
content.Add(new StringContent("12", Encoding.UTF8), "userId");
content.Add(new StringContent("78", Encoding.UTF8), "noOfAttendees");
content.Add(new StringContent("chennai", Encoding.UTF8), "locationName");
content.Add(new StringContent("32.56", Encoding.UTF8), "longitude");
content.Add(new StringContent("32.56", Encoding.UTF8), "latitude");
Console.Write(content);
// upload the file sending the form info and ensure a result.
// it will throw an exception if the service doesn't return a valid successful status code
await client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
#
is invalid in a MIME boundary.
From RFC 2046:
The only mandatory global parameter for the "multipart" media type is the boundary parameter, which consists of 1 to 70 characters from a set of characters known to be very robust through mail gateways, and NOT ending with white space. (If a boundary delimiter line appears to end with white space, the white space must be presumed to have been added by a gateway, and must be deleted.) It is formally specified by the following BNF:
boundary := 0*69<bchars> bcharsnospace bchars := bcharsnospace / " " bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?"
So basically, you should use a boundary string which doesn't contain a #
. I'd suggest using one which doesn't contain hyphens either, just because the boundary lines will have hyphens anyway (at the start and end). Having them in the boundary as well is a bit confusing.
Unless you need a specific boundary, I suggest you just call the parameterless constructor, which will use a random GUID as the boundary.
See more on this question at Stackoverflow