处理程序未返回图像。如果我删除条件语句,处理程序将返回图像。这是我的代码
public void ProcessRequest(HttpContext context)
{
string sid = "JUN15MBACHN001";
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select suppassportphoto from studdetails where sregno=" + sid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
Byte[] br = (Byte[])dr[0];
if (br.Length > 1)
{
context.Response.BinaryWrite((Byte[])dr[0]);
}
else
{
string path = context.Server.MapPath("~/image/emptymalepic.jpg");
byte[] byteArray = File.ReadAllBytes(path);
context.Response.BinaryWrite(byteArray);
}
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
我不知道我哪里错了?任何帮助将不胜感激。
最佳答案
首先,我建议以不同的方式进行转换,因为您的代码可能会导致无效转换异常:
Byte[] br = dr[0] as Byte[];
然后检查是否为空
if (br != null && br.Length > 1)
然后写入文件:
context.Response.ContentType = "image/jpeg"; // or whatever type you're using
context.Response.BinaryWrite(br);
并替换
context.Response.End();
与
HttpContext.Current.ApplicationInstance.CompleteRequest();
因为我注意到有些浏览器不喜欢 Response.End()
希望这是有用的。祝你好运!
关于c# - 通用处理程序不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30369826/