尝试在ASP.NET中使用图像处理程序时出错

时间:2011-11-13 20:47:53

标签: c# asp.net blob httphandler

我从指南中获取了以下代码以便对其进行测试,并且遇到错误,说Object reference not set to an instance of an object.

请注意,这不是我的代码,因此此问题与解密相关。

   public class ProductImageHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Int32 id;
            if (context.Request.QueryString["id"] != null)
                id = Convert.ToInt32(context.Request.QueryString["id"]);
            else
                throw new ArgumentException("No parameter specified");

            context.Response.ContentType = "image/jpeg";
            Stream strm = GetFromDB(id);
            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
            //context.Response.BinaryWrite(buffer);
        }

        public Stream GetFromDB(int id)
        {
            string conn = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            SqlConnection connection = new SqlConnection(conn);
            string sql = "SELECT Image FROM Products WHERE ID = @ID";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@ID", id);
            connection.Open();
            object img = cmd.ExecuteScalar();
            try
            {
                return new MemoryStream((byte[])img);
            }
            catch
            {
                return null;
            }
            finally
            {
                connection.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }

错误发生在以下行:

int byteSeq = strm.Read(buffer, 0, 4096);

有没有人知道问题可能是什么?

5 个答案:

答案 0 :(得分:0)

嗯,该行唯一的成员访问权限在strm上,所以我认为它是null引用。

检查特定查询的GetFromDB返回值。我认为如果找不到null,它将返回id

Stream strm = GetFromDB(id);

要解决此问题,请执行以下操作:

  • 更新GetFromDB以不返回null
  • 检查传入的id以确保其有效
  • 在使用之前检查strm是否为null

答案 1 :(得分:0)

这可能是因为GetFromDB返回null。在GetFromDB中捕获异常时不应返回null,或者如果这样做,则应测试返回值不为null。尽量不要捕获异常,这将显示问题所在。

答案 2 :(得分:0)

很明显,这一行返回null:

Stream strm = GetFromDB(id);

检查该方法是否包含正确的实现以及是否存在提供的ID。

答案 3 :(得分:0)

当抛出异常时,你的GetFromDB方法返回null(顺便说一下,ick)...所以我建议单步执行它以找出原因。

答案 4 :(得分:0)

如果你把对象img = cmd.ExecuteScalar(); try块内的行可以修改catch以捕获实际的异常对象,而不是仅返回null。