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

3
我正在尝试为我的上传图片操作创建集成测试。从浏览器生成的原始请求如下所示:;
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个回答

7

修改子项HttpContent的Headers,而不是在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;

谢谢。我明天会尝试并反馈。 - Teoman shipahi
这个帮了我好几个小时的搜索! - user890332

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接