C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在c#HttpClient 4.5中发布multipart / form-data大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
问题

我正在尝试发布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;
    }
}
@H_450_13@解决方法
这种方法适合我.您可以使用表单数据和文件
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所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。