从 HttpHandler 中的 HttpWebRequest 获取图像作为响应

Get Image as a response from HttpWebRequest in HttpHandler

我在 Asp.Net MVC 项目中使用 HttpHandler。我有另一个 MVC API 项目,return 图像作为响应。使用 HttpWebRequest 我可以调用 API,代码没有错误,但我无法在页面中查看图像。

我的代码:

HttpHandler 代码:

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" />

如果您正确设置 ContentType 并简单地将响应流复制到输出,这将起作用,如下所示:

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