我正在尝试发布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; }}解决方法 这种方法适合我.您可以使用表单数据和文件
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#HttpClient 4.5中发布multipart / form-data所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)