簡體   English   中英

如何將請求從Asp.net MVC發送到multipart / form-data類型的外部api

[英]how to send request from Asp.net MVC to external api in multipart/form-data type

我正在嘗試將控制器上載的文件發送到項目外的另一個API。 目標API接受multipart / form-data類型的請求

我從當前上下文中讀取了上傳的文件

我的問題是如何發送請求multipart / form-data並將附加的上傳文件附加在上面

我嘗試在客戶端執行此操作,但由於跨域問題而無法執行。

檢查此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... } } 

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM