Csharp/C#教程:在c#HttpClient 4.5中发布multipart / form-data分享


在c#HttpClient 4.5中发布multipart / form-data

问题

我正在尝试发布API以将数据发送到API,该API调用我的内部API服务以将该数据发送到其他API i服务。 实体包含带文件的属性。 这只将文件发送到另一个派生,但NameSender属性不随文件一起发送。

实体

public class Email { public string NameSender{ get; set; } public List 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 = $"https://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; } } 

这种方法适合我。 您可以使用表单数据和文件

上述就是C#学习教程:在c#HttpClient 4.5中发布multipart / form-data分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public async Task 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("https://filestorageurl", formDataContent)) { return res.IsSuccessStatusCode; } } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1018152.html

(0)
上一篇 2022年1月3日
下一篇 2022年1月3日

精彩推荐