簡體   English   中英

ASP.Net MVC 從外部 API 返回文件作為附件

[英]ASP.Net MVC return file as attachment from external API

我有一個 API 端點,它以附件形式返回文件。 例如,如果我訪問 www.myfileservice.com/api/files/download/123 我可以直接下載文件。 我的要求是在另一個 ASP.Net MVC 項目中使用這個端點。 因此,如果用戶點擊 www.mymvcapplication.com/File/DownloadDocument/123 它也應該下載相同的文件。 在內部,action 方法應該調用文件服務 API 並按原樣返回結果。 這是我正在使用的代碼:

文件控制器.cs:

public HttpResponseMessage DownloadDocument(int Id)
{
    return new DocumentClient().DownloadDocument(Id);
}

文檔客戶端.cs:

public class DocumentClient
{
    private string documentServiceURL = string.Empty;
    private static string downloadDocumentUri = "api/files/download/";

    protected HttpClient documentClient = null;

    public DocumentClient()
    {
        documentServiceURL = "www.myfileservice.com";
        documentClient = new HttpClient();
        documentClient.BaseAddress = new Uri(documentServiceURL);
    }

    public HttpResponseMessage DownloadDocument(int Id)
    {
        return documentClient.GetAsync(String.Format("{0}/{1}", downloadDocumentUri, Id)).Result;
    }
}

上面的代碼沒有給出任何錯誤,只是在瀏覽器窗口中打印響應(Content-Length、Content-Disposition 等)。 我需要下載文件。

我認為最好的方法是從您的 controller 返回一個 FileResult:

public FileResult DownloadDocument(int Id)
{
    var document = new DocumentClient().DownloadDocument(Id);
    //do the transformation here
    //...
    //I don't know what is your file's extension, please replace "application/zip" if 
    //needed
    return File(finalResult, "application/zip", fileName);
}

暫無
暫無

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

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