Search code examples
asp.net-mvc-3c#-4.0streamhttpwebresponsefileresult

MVC ASP.NET Return response.GetResponseStream() as FileResultStream


I am trying to write a controller that creates and makes a HttpWebRequest to a service that returns an Image. I then want to return this image as a FileResult. How do I go about doing that. I have tried the code below but it returns a corrupted image instead of the full image:

public FileResult SomeAction()
{
    var request = Make some request here

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        string contentType = response.ContentType;
        return File(response.GetResponseStream(),contentType);
    }
}

Thanks


Solution

  • Since you fail to mention how "it doesn't work", all I can tell you is that in general what you're doing should work. However, i'm unsure of where the response stream is actually read. Since you're placing a return inside a using, it may be that the stream is being disposed of before the stream is actually read. Try removing the using statement, and just doing something like this:

    var response = request.GetResponse();
    File(response.GetResponseStream(), response.ContentType);
    

    if that doesn't work, then verify that response is actually returning a content type, and a valid stream.

    EDIT:

    It would seem that I was correct, the filestream gets closed before it's read if you wrap it in a using. You don't have to worry about disposing of the stream as File will dispose of it when it's done with it.

    See this other question:

    How do I dispose my filestream when implementing a file download in ASP.NET?