Mic*_*per 57 c# asp.net asp.net-web-api dotnet-httpclient
我有一个WebApi服务从一个简单的表单处理上传,如下所示:
<form action="/api/workitems" enctype="multipart/form-data" method="post">
<input type="hidden" name="type" value="ExtractText" />
<input type="file" name="FileForUpload" />
<input type="submit" value="Run test" />
</form>
Run Code Online (Sandbox Code Playgroud)
但是,我无法弄清楚如何使用HttpClient API模拟相同的帖子.这个FormUrlEncodedContent
位很简单,但是如何将文件内容与名称一起添加到帖子中?
Mic*_*per 121
经过多次试验和错误,这里的代码实际上有效:
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("Foo", "Bar"),
new KeyValuePair<string, string>("More", "Less"),
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Foo.txt"
};
content.Add(fileContent);
var requestUri = "/api/action";
var result = client.PostAsync(requestUri, content).Result;
}
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*tad 10
你需要寻找各种子类HttpContent
.
您创建一个多形式的http内容并添加各种部分.在您的情况下,您有一个字节数组内容和表单url编码沿着以下行:
HttpClient c = new HttpClient();
var fileContent = new ByteArrayContent(new byte[100]);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFilename.txt"
};
var formData = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("name", "ali"),
new KeyValuePair<string, string>("title", "ostad")
});
MultipartContent content = new MultipartContent();
content.Add(formData);
content.Add(fileContent);
c.PostAsync(myUrl, content);
Run Code Online (Sandbox Code Playgroud)
Thi*_*PXP 10
谢谢@Michael Tepper的回答.
我不得不将附件发布到MailGun(电子邮件提供商),我不得不稍微修改它以便接受我的附件.
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("form-data") //<- 'form-data' instead of 'attachment'
{
Name = "attachment", // <- included line...
FileName = "Foo.txt",
};
multipartFormDataContent.Add(fileContent);
Run Code Online (Sandbox Code Playgroud)
这里供将来参考.谢谢.