【问题标题】:how to send request from Asp.net MVC to external api in multipart/form-data type如何将请求从 Asp.net MVC 发送到 multipart/form-data 类型的外部 api
【发布时间】:2016-07-25 18:35:26
【问题描述】:

我正在尝试将上传的文件从我的控制器发送到我的项目之外的另一个 API。 目标 API 接受 multipart/form-data 类型的请求

我从当前上下文读取上传的文件

我的问题是如何发送请求 multipart/form-data 并在其上附加上传的文件

我尝试在客户端做,但由于跨域问题,我做不到。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api


    【解决方案1】:

    您需要向该 API 发出 Http 请求。

    这是一个如何使用HttpClient 发出 Http 请求并将文件作为附件发送的示例。

    filePath参数可以是MVC上传的文件。

    public async Task SendAsync(string filePath)
    {
        string url = "http://localhost/api/method";
    
        MultipartFormDataContent content = new MultipartFormDataContent();
    
        var fileContent = new StreamContent(File.OpenRead(filePath));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        fileContent.Headers.ContentDisposition.FileName = "file.txt";
        fileContent.Headers.ContentDisposition.Name = "file";
        fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
        content.Add(fileContent);
    
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            HttpResponseMessage response = await client.PostAsync(url, content);
        }
    }
    

    【讨论】:

      【解决方案2】:

      查看http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

      using System.Net.Http;
      using System.Web.Http;
      using System.Web.Http.Cors;
      
      namespace WebService.Controllers
      {
          [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
          public class TestController : ApiController
          {
              // Controller methods not shown...
          }
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多