在C#HttpClient 4.5中发布multipart/form-data [英] post multipart/form-data in c# HttpClient 4.5

查看:274
本文介绍了在C#HttpClient 4.5中发布multipart/form-data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to post API to send data to API which calls my internal API service to send that data to other API i service. Entity contains property with files . this send only file to the other derive but the NameSender property not send with the file.

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;
    }
}

推荐答案

此方法适用于我.您可以使用表格数据和文件

This method works for me. You can use form data and file

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆