user666
user666

Reputation: 332

How to set the Content Type of HttpClient

I'm uploading an image.

I want to set the value of Content-Type="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN"

using the code :

HttpRequestMessage request=new HttpRequestMessage();
request.Content.Headers.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";

or request.Header.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";

it will cause an error:one of the identified items was in an invalid format.

if only set of "multipart/form-data" it will be ok but can not upload the file.

How to set it?

Upvotes: 1

Views: 4057

Answers (1)

Leo Zhu
Leo Zhu

Reputation: 15021

Here are some code snippets you can refer to:

  using (var client = new HttpClient())
  using (var fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)
  using (var streamContent = new StreamContent(fileStream))
  {
     streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
     streamContent.Headers.ContentDisposition.Name = "\"file\"";
     streamContent.Headers.ContentDisposition.FileName = "\"" + fileName + "\"";
     streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
     string boundary = "WebKitFormBoundaryFoxUxCRayQhs5eNN";

     var fContent = new MultipartFormDataContent(boundary);
     fContent.Headers.Remove("Content-Type");
     fContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
     fContent.Add(streamContent);

     var response = await client.PostAsync(new Uri(url), fContent);
     response.EnsureSuccessStatusCode();
  }

if you use HttpWebRequest,you could refer to this:https://stackoverflow.com/a/20000831/10768653

Upvotes: 1

Related Questions