在 c# HttpClient 4.5 中发布 multipart/form-data
Posted
技术标签:
【中文标题】在 c# HttpClient 4.5 中发布 multipart/form-data【英文标题】:post multipart/form-data in c# HttpClient 4.5 【发布时间】:2018-03-12 06:36:55 【问题描述】:问题
我正在尝试发布 API 以将数据发送到 API,该 API 调用我的内部 API 服务将该数据发送到其他 API i 服务。实体包含带有文件的属性。这仅将文件发送到另一个派生,但 NameSender 属性不与文件一起发送。
实体
public class Email
public string NameSender get; set;
public List<IFormFile> Files get; set;
API
[Consumes("multipart/form-data")]
[HttpPost]
public IActionResult SendEmail([FromForm]Entity entity)
try
string Servicesfuri = this.serviceContext.CodePackageActivationContext.ApplicationName + "/" + this.configSettings.SendNotificationServiceName;
string proxyUrl = $"http://localhost:this.configSettings.ReverseProxyPort/Servicesfuri.Replace("fabric:/", "")/api/values/Send";
//attachments
var requestContent = new MultipartFormDataContent();
foreach (var item in entity.Files)
StreamContent streamContent = new StreamContent(item.OpenReadStream());
var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
requestContent.Add(fileContent, item.Name, item.FileName);
HttpResponseMessage response = this.httpClient.PostAsync(proxyUrl, requestContent).Result;
if (response.StatusCode != System.Net.HttpStatusCode.OK)
return this.StatusCode((int)response.StatusCode);
return this.Ok(response.Content.ReadAsStringAsync().Result);
catch (Exception e)
throw e;
【问题讨论】:
【参考方案1】:这种方法对我有用。您可以使用表单数据和文件
public async Task<bool> Upload(FileUploadRequest model)
var httpClientHandler = new HttpClientHandler()
Proxy = new WebProxy("proxyAddress", "proxyPort")
Credentials = CredentialCache.DefaultCredentials
,
PreAuthenticate = true,
UseDefaultCredentials = true
;
var fileContent = new StreamContent(model.File.OpenReadStream())
Headers =
ContentLength = model.File.Length,
ContentType = new MediaTypeHeaderValue(model.File.ContentType)
;
var formDataContent = new MultipartFormDataContent();
formDataContent.Add(fileContent, "File", model.File.FileName); // file
formDataContent.Add(new StringContent("Test Full Name"), "FullName"); // form input
using (var client = new HttpClient(handler: httpClientHandler, disposeHandler: true))
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenString);
using (var res = await client.PostAsync("http://filestorageurl", formDataContent))
return res.IsSuccessStatusCode;
【讨论】:
以上是关于在 c# HttpClient 4.5 中发布 multipart/form-data的主要内容,如果未能解决你的问题,请参考以下文章
如何在 C# (.NET 4.5) 中为 HttpClient.GetAsync(URI) 创建回调?
在 .net 4.5 中尝试使用 HttpClient 使 cookie 无法响应
Atitit.http httpclient实践java c# .net php attilax总结