gpt4 book ai didi

c# - 在 Web API 中设置 "Content-Disposition"HTTP header

转载 作者:行者123 更新时间:2023-11-30 20:30:18 25 4
gpt4 key购买 nike

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

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; 的数据的第二部分名称=“文件上传”; filename="image.jpg"

我怎样才能做到这一点?

问题总结:

enter image description here

最佳答案

修改子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;

关于c# - 在 Web API 中设置 "Content-Disposition"HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45044607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com