Search code examples
c#asp.net-mvchttphandlerhttpwebresponse

Get Image as a response from HttpWebRequest in HttpHandler


I am using HttpHandler in my Asp.Net MVC project. I have another MVC API project that return image as a response. Using HttpWebRequest I am able to call the API, there is no error in code but I can't view the Image in the page.

My Code:

HttpHandler code:

var currentResponse = HttpContext.Current.Response;

string URL = "http://localhost:50417/API/GetThumbnail";
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                    request.KeepAlive = false;
                    request.ProtocolVersion = HttpVersion.Version10;
                    request.Method = "GET";
                    request.Timeout = 30000;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    StreamReader streamr = new StreamReader(response.GetResponseStream());


                    currentResponse.Write(streamr.ReadToEnd());

RouteConfig.cs

routes.Add(new Route("Thumbnail/getImage", new ThumbnailImageRouteHandler()));

index.csHtml

<img src="/Thumbnail/getImage" />

Solution

  • This works if you set the ContentType properly and simply copy the response stream to the output, like this:

    response.GetResponseStream().CopyTo(currentResponse.OutputStream);
    currentResponse.ContentType = response.ContentType;