如何从Asp.net MVC向multipart / form-data类型的外部api发送请求

时间:2016-07-25 09:33:06

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

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

类型的请求

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

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

我试图在客户端进行,但我不能,因为跨域问题。

2 个答案:

答案 0 :(得分:0)

选中此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...
    }
}

答案 1 :(得分:0)

您需要向该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);
    }
}