我正在尝试编写一个httphandler来检索图像网址,然后将其显示在图像控件上,我正在使用此代码,但它无法正常工作
OleDbConnection mDB = new OleDbConnection(
ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
mDB.Open();
OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
context.Response.BinaryWrite((byte[])rdr[0]);
mDB.Close();
context.Response.End(); */
抱歉,我在SELECT语句中引起了混淆,pProductId不包含图像的URL,而pProductImage是包含URL的字段。我正在使用Id来识别要相应显示的图像。
这是我的预期输出:
<img src="ImgHandler.ashx?pProductId=2" alt="" />
我无法放置图片这是我错误消息的链接:http://imgur.com/Cix67
答案 0 :(得分:1)
这是一个两步回答。 在页面中,您可以执行以下操作:
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
using (OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.Write("<img src=\"ImgHandler.ashx?pProductId=");
context.Response.Write((int)rdr[0]); // I suppose pProductId is an int, adapt accordingly
context.Response.Write("\" />");
}
}
}
并在隐式触发的HTTP处理程序中,如下所示:
public class MyHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
// select the file data (I put pData here as a placeholder, and assume it will be a byte[])
using (OleDbCommand cmd = new OleDbCommand("select pData from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.ContentType = "image/png";// put the content type here
context.Response.BinaryWrite((byte[])rdr[0]);
}
}
}
}
}
请注意使用模式,确保在使用后正确清理资源。另外,理想情况下,您可以使用适当的缓存HTTP标头(如if-modified-since)在客户端缓存数据,但这是另一个故事......