0

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.

astm1982
  • 145
  • 13
  • try this : https://stackoverflow.com/questions/28410597/download-file-prompt-when-using-webapi-httpresponsemessage – Mike Oct 16 '19 at 10:32
  • This may be of assistance: https://stackoverflow.com/questions/23884182/how-to-get-byte-array-properly-from-an-web-api-method-in-c/23884972 – scgough Oct 16 '19 at 10:49

1 Answers1

0

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);
}
devGirl
  • 58
  • 4