简体   繁体   中英

ASP.Net MVC return file as attachment from external API

I have an API endpoint that returns file as attachment. for example if I access www.myfileservice.com/api/files/download/123 I could download the file directly. My requirement is to use this endpoint in another ASP.Net MVC project. So if the user hits www.mymvcapplication.com/File/DownloadDocument/123 it should also download the same file. Internally the action method should call the file service API and return the result as it is. This is the code I am using:

FileController.cs:

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

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

The code above is not giving any error but only printing the response in browser window(Content-Length, Content-Disposition etc). I need to download the file instead.

I think the best is to return a FileResult from your controller:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM