使用HttpClient发送MultipartFormDataContent时设置ContentType标头

时间:2014-10-23 21:57:25

标签: asp.net-mvc asp.net-web-api

我使用HttpClient使用下面的代码将文件上传到WebAPI资源。由于我使用的是MultipartFormDataContent,因此请求消息内容类型设置为multipart / form-data。在WebAPI中,我检查内容标题只允许文本/普通媒体类型。那么,如果我使用带有MultipartFormDataContent的HttpClient,我在哪里设置文件类型的内容标题。

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

2 个答案:

答案 0 :(得分:14)

您可以使用StreamContent对象的Headers属性设置ContentType属性,例如,在我的情况下,我上传图像并使用以下代码:

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

答案 1 :(得分:1)

您可以使用以下代码设置ContentType:

            var formData = new MultipartFormDataContent();
           
            var bytes = await video.GetBytes();
           
            var streamContent = new StreamContent(new MemoryStream(bytes));
            streamContent.Headers.Add("Content-Type", video.ContentType);
            streamContent.Headers.Add("Content-Disposition", $"form-data; name=\"{video.FileName}\"; filename=\"{video.FileName}\"");
            
            formData.Add(streamContent, "file", $"{video.FileName}");
            
            var request = new HttpRequestMessage(HttpMethod.Post, $"api/client/uploadVideo?deviceOs={deviceOs}")
            {
                Content = formData,
            };

            request.Headers.Add("accept", "application/json");
            
            var response = await httpClient.SendAsync(request);