I am trying to create Handler, and I am trying to have it return a default picture when it returns a null value. But when I access this via a page using the second code bit below, I get an error image. But If I go directly to the page Image.ashx?id=28 and no images exist I get my default image, why isnt it showing up on my page? And If an image does exist it displays that image on the page and if directly called.
Thanks
My Image.ashx File:
public void ProcessRequest(HttpContext ctx)
{
string id = ctx.Request.QueryString["id"];
SqlConnection con = new SqlConnection(CONN INFO);
SqlCommand cmd = new SqlCommand("SELECT EventInviteImage FROM Events WHERE EventID = @EventID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@EventID", id);
byte[] pict = null;
try
{
con.Open();
pict = (byte[])cmd.ExecuteScalar();
ctx.Response.ContentType = "image/pjpeg";
ctx.Response.BinaryWrite(pict);
}
catch
{
ctx.Response.Write("<img src='/images/defaultevent.jpg'>");
}
finally
{
con.Close();
}
}
public bool IsReusable
{
get
开发者_如何学Python {
return true;
}
}
Calling Image:
<img src="Image.ashx?id=28" />
try
{
...
ctx.Response.ContentType = "image/pjpeg";
ctx.Response.BinaryWrite(pict);
}
catch
{
ctx.Response.ContentType = "image/pjpeg";
ctx.Response.Write("<img src='/images/defaultevent.jpg'>");
}
You are doing very different things in the try
and the catch
- instead of writing a string
in your catch, you should be returning the file:
catch
{
ctx.Response.WriteFile("path to defaultevent.jpg");
}
精彩评论