Drake
Drake

Reputation: 2713

Creating MediaTypeWithQualityHeaderValue throws FormatException

I am creating an instance of MediaTypeWithQualityHeaderValue like this:

var m = new MediaTypeWithQualityHeaderValue("multipart/form-data; boundary=acrcloud***copyright***2015***8d467c7c10a7062");

It throws a FormatException, so I guess the string that I passed doesn't follow the standard convention. It's supposed to be the content type that my client API requires. I then need to add it to my HttpClient to make the API call like so:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(m);

My first question is, how can I fix the string that I passed so that the format is correct?

My second question is, is it possible to set the content type to this string, even though it is not formatted correctly?

EDIT

To clarify, I'm trying to do the equivalent of this:

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=acrcloud***copyright***2015***8d467c7c10a7062";

But with using the HttpClient class instead.

Upvotes: 0

Views: 1338

Answers (1)

ckuri
ckuri

Reputation: 4545

This fails becaus Multipart/form-type is not a media type, but a content type. The content is defined by providing the HTTP send method (GetAsync, PostAsync, ...) with the proper HttpContent object. For multipart contents a special HttpContent class exists which allows the encapsulation of multiple HttpContents. So basically it goes like this:

using (var client = new HttpClient())
{
  var content = new MultipartFormDataContent("acrcloud***copyright***2015***8d467c7c10a7062");
  content.Add(new StringContent("value"), "key");
  content.Add(new StreamContent(stream)
  {
    Headers =
    {
      ContentDisposition = new ContentDispositionHeaderValue(DispositionTypeNames.Attachment) { Filename = "Filename.txt" }
    }
  }, "filekey");
  await PostAsync("http://www.example.com", content);
}

Upvotes: 1

Related Questions