1

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

4
  • I had a similar problem. Does this post help: stackoverflow.com/questions/9185494/… Commented Apr 26, 2012 at 22:31
  • I am trying to avoid using the HttpContext.Response.OutputStream directly. Commented Apr 26, 2012 at 22:34
  • saying "It does not work" is like going to a car mechanic and saying "it makes a funny noise". Commented Apr 26, 2012 at 22:37
  • It returns a corrupted image result, rather than the full image Commented Apr 26, 2012 at 22:38

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.