1

我正在使用自定义 ashx HttpHandler 从数据库中检索 gif 图像并将其显示在网站上 - 当图像存在时,它工作得很好。

但是,在某些情况下图像将不存在,并且我希望保存图像的 html 表变得不可见,因此不显示“找不到图像”图标。

但是由于 HttpHandler 不是同步的,我在 Page_Load 检查图像大小的所有尝试都受挫。关于如何实现这一点的任何想法?

编辑::

到目前为止,情况如下:

这是我的处理程序:

 public void ProcessRequest(HttpContext context)
        {
            using (Image image = GetImage(context.Request.QueryString["id"]))
            {
                context.Response.ContentType = "image/gif";
                image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
            }
        }

        private Image GetImage(string id)
        {
            try
            {
                System.IO.MemoryStream ms;
                byte[] rawImage;
                Image finalImage;
                // Database specific code!      
rawImage = getImageFromDataBase(id);

                ms = new System.IO.MemoryStream(rawImage, 0, rawImage.Length);
                ms.Write(rawImage, 0, rawImage.Length); 

                finalImage = System.Drawing.Image.FromStream(ms, true);

                return finalImage;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("ERROR:::: " + ex.Message);
                return null;
            }
        }

我像这样使用它:

myImage.ImageUrl = "Image.ashx?id=" + properId;
4

4 回答 4

1

但是,在某些情况下图像将不存在,并且我希望保存图像的 html 表变得不可见,因此不显示“找不到图像”图标。

解决此问题的最简单方法是在返回之前检查图像是否存在于 Http 处理程序中(在 image.ashx 文件中。)。

  if(image == null) {image = new blankImage();}

如果不存在,请用空白图像替换它。这样,这不是未找到图像的图标。如果您真的希望它消失并且不保留图像大小,只需将空白图像设置为 1x1 正方形。

于 2010-06-08T18:00:16.173 回答
0

由于 ashx 在 page_load 之后执行,因此您可以使其返回 1x1 正方形,但是如果您想完全隐藏该列,由于生命周期,您将遇到一些问题。

您可以在页面上创建一个占位符,并动态构建您的表格。如果您可以避免使用 ashx,而是在代码隐藏中进行图像检索和渲染,您将能够知道何时隐藏该列

于 2010-06-08T18:39:17.103 回答
0

你不能只使用 NullReferenceException,还是我误解了这个问题?

try
{ 
    //try to get the photo
}
catch (NullReferenceException)
{
    //handle the error
}

您也可以检查image == null我是否认为这在您的情况下可能更有意义。

于 2010-06-08T17:57:56.453 回答
0

尽管这会使页面两次获取图像,但我使用的是小图像并且在很少的页面上,所以我认为这是值得的。

这是我添加到页面的代码:

public static bool CheckImageExistance(string url)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
                request.Method = "HEAD";       

                request.Credentials = CredentialCache.DefaultCredentials;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
                response.Close();
                return (response.StatusCode == HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                return false;
            }

它按预期工作。感谢所有的投入。

于 2010-06-09T15:03:18.083 回答