elector
elector

Reputation: 1339

MVC controller, get a file from WebAPI and return as FileResult

My controller needs to call a WebAPI method which will return an HttpResponseMessage object with a pdf file in the Content. I need to return this file immediately as a FileResult object from the the controller. I was experimenting with a number of solutions put together from code found all around but it seems that all file saving methods as async and I run into problems returning the file as FileResult immediately in the same controller method. What is the best approach in this scenario?

Some code I have tried:

System.Threading.Tasks.Task tsk = response.Content.ReadAsFileAsync(localPath, true).ContinueWith(
                    (readTask) =>
                    {
                        Process process = new Process();
                        process.StartInfo.FileName = localPath;
                        process.Start();
                    });
                await tsk;

                return File(localPath, "application/octetstream", fileName);

This was my main idea, get the file from the response Content and return it as FileResult. But this throws Access Denied on await tsk.

Upvotes: 1

Views: 4790

Answers (1)

Adrien Siffermann
Adrien Siffermann

Reputation: 116

You don't have to save the file on your disk as a file, you can simply deal with a Stream like this:

public async Task<FileResult> GetFile()
{
    using (var client = new HttpClient())
    {
        var response = await client.GetAsync("https://www-asp.azureedge.net/v-2017-03-27-001/images/ui/asplogo-square.png");
        var contentStream = await response.Content.ReadAsStreamAsync();

        return this.File(contentStream, "application/png", "MyFile.png");
    }
}

Hope that helps!

Upvotes: 4

Related Questions