1

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.

2
  • 1
    Can you share the code you already tried to use? Apr 13, 2017 at 11:36
  • It's a mess, I am not sure what to add... I'll add some code.
    – elector
    Apr 13, 2017 at 11:46

1 Answer 1

4

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!

1
  • And I was complicating it so much! Thank you Adrien!
    – elector
    Apr 13, 2017 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.