在Web API中设置“Content-Disposition”HTTP标头

时间:2017-07-11 21:16:50

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

我正在尝试为我的上传图片操作创建集成测试。 从浏览器创建的原始请求如下所示;

POST /api/UpdateImage HTTP/1.1
Host: upload.qwe.com
Authorization: bearer KuThe6Wx/CW1TO/HVS+u3Tov3MRh8qTMDrSvQ09nMnP4OgYp
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1
Content-Length: 375488
Accept-Language: en-us
Accept: */*
Connection: keep-alive
User-Agent: Chrome
Pragma: no-cache
Cache-Control: no-cache

--Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1
Content-Disposition: form-data; name="fileName"

image.jpg
--Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1
Content-Disposition: form-data; name="fileUpload"; filename="image.jpg"
Content-Type: image/jpeg

我的集成测试代码;

MultipartContent multipartContent = new MultipartContent();
 multipartContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1");
ContentDispositionHeaderValue contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileName"
            };
            multipartContent.Headers.ContentDisposition = contentDispositionHeaderValue;
// StreamContent
        FileStream fileStream = File.Open(@"./Assets/" + fileName, FileMode.Open);
        StreamContent stream = new StreamContent(fileStream);
        multipartContent.Add(stream);
httpRequestMessage.Content = multipartContent;
        return httpRequestMessage;

但是我无法设置具有Content-Disposition: form-data; name="fileUpload"; filename="image.jpg"

的数据的第二部分

我怎样才能做到这一点?

问题摘要:

enter image description here

1 个答案:

答案 0 :(得分:4)

修改子HttpContent的标题,而不是MultipartFormDataContent

        var main = new MultipartFormDataContent(Guid.NewGuid().ToString());
        HttpContent content = new StringContent("image.jpg");
        content.Headers.Clear();
        content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "fileName" };
        main.Add(content);

        content = new StreamContent(new MemoryStream(new byte[] { 1, 2, 3 }));//your file stream, or other base64 string
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
        content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "fileUpload", FileName="image.jpg" };
        main.Add(content);

        req.Content = main;