我正在使用 ashx 请求处理程序来检索图像,但我在 ashx 文件中的断点没有被命中。当我使用 firebug 时,我可以看到请求正在返回 404,这让我觉得我需要配置一些设置才能找到 ashx 文件。
我正在使用 visual studio 2008 和 .net 3.5。
ASHX 文件
namespace hybrid.content.Handlers
{
public class DB_Images : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 image_id;
if (context.Request.QueryString["id"] != null)
image_id = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = GetImageFromDatabase(image_id);
if (strm != null)
{
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 GetImageFromDatabase(int image_id)
{
SqlConnectionStringBuilder connstr = new SqlConnectionStringBuilder();
//connstr.InitialCatalog = "dummy";
//connstr.UserID = "sa";
//connstr.Password = "password";
//connstr.DataSource = "source";
connstr.InitialCatalog = "smsdb";
connstr.UserID = "user";
connstr.Password = "password";
connstr.DataSource = "10.31.4.79";
SqlConnection conn = new SqlConnection(connstr.ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
// cmd.CommandText = "select image from cis_images where image_id = @p_image_id";
cmd.CommandText = "select image from test_images where image_id = @p_image_id";
cmd.Parameters.AddWithValue("@p_image_id", image_id);
conn.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
conn.Close();
conn.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
页面点击事件
protected void Button1_Click(object sender, EventArgs e)
{
Image1.ImageUrl = "~/DB_Images.ashx?id=" + TextBox1.Text;
}
ashx html
<%@ WebHandler Language="C#" CodeBehind="DB_Images.ashx.cs" Class="hybrid.content.Handlers.DB_Images" %>
除了该引用之外没有任何 html。
我是否缺少某些东西才能让它发挥作用?
最佳答案
在我的例子中,我将 ashx 文件标记为 None 内容类型而不是 Content,即 Properties -> Build Action 因为它应该是 Content,这意味着发布网站时未包含 ashx 文件。
关于c# - asp.net ashx 请求 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912463/