将图像写入 ASHX

Writing a image to ASHX

我正在编辑一个旧的 .NET 3.5 站点,需要它来下载图像,然后将其提供给请求。基本上是通过。

数据以正确的大小发送,但未显示图像。

public class AppImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        var url = "http://static.idolator.com/uploads/2015/10/adele-hello.jpg";

        HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(url);
        WebResponse imageResponse = imageRequest.GetResponse();
        Stream responseStream = imageResponse.GetResponseStream();

        byte[] buffer = new byte[imageResponse.ContentLength];
        int read;
        Stream output = new MemoryStream();
        while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
        responseStream.Close();

        HttpResponse r = context.Response;
        r.ContentType = "image/jpg";
        r.BinaryWrite(buffer);

    }

我没有阅读全文。

我用它来获取完整的字节数组,然后它起作用了

public static byte[] ReadFully(Stream input)
{
 byte[] buffer = new byte[16*1024];
 using (MemoryStream ms = new MemoryStream())
 {
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        ms.Write(buffer, 0, read);
    }
    return ms.ToArray();
 }
}