我有一个 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>
但是,我不知道如何使用 HttpClient API 模拟同一篇文章。这FormUrlEncodedContent
位很简单,但是如何将带有名称的文件内容添加到帖子中?
经过多次试验和错误,下面是实际有效的代码:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)