Setting ContentType header when sending MultipartFormDataContent using HttpClient

I am using HttpClient to upload a file to a WebAPI resource using the below code. Since I am using MultipartFormDataContent, the content type of the request message is set to multipart / form-data. In WebAPI, I check the content header to only allow the text / regular media type. So where do I set the content header for the file type if I am using HttpClient with MultipartFormDataContent.

try
{
    var content = new MultipartFormDataContent();

    string filePath = Server.MapPath("~/Content/" + "demo.txt");

    var filestream = new FileStream(filePath, FileMode.Open);

    var fileName = System.IO.Path.GetFileName(filePath);

    content.Add(new StreamContent(filestream), "file", fileName);

    var requestMessage = new HttpRequestMessage()
    {
            Method = HttpMethod.Post,
            Content = content,
            RequestUri = new Uri("http://localhost:64289/api/uploads/"), 
        };

    var client = new HttpClient();

    client.DefaultRequestHeaders.Add("Accept", "application/json");

    HttpResponseMessage response = await client.SendAsync(requestMessage);

    if (response.IsSuccessStatusCode)
    {
                    /// 
    }
}
catch (Exception e)
{
                throw;
}

      

+3


source to share


1 answer


You can set the ContentType property using the Headers property of the StreamContent object, for example, in my case I load an image and use the following code:



        StreamContent image = new StreamContent(fileStream);
        image.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(imagePath));

      

+5


source







All Articles