我有一个ASP.NET网站的通用处理程序(.ashx),它允许我从存储在SQL Server数据库中的二进制数据中查看图像文件:
public class ImageProvider : IHttpHandler {
public string connString = "...";
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
string sqlSelectQuery = "select img from Subjects Where [Id] = 'XXXX'";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(sqlSelectQuery, conn);
byte[] img = (byte[])cmd.ExecuteScalar();
context.Response.BinaryWrite(img);
}
我目前正在使用简单的Response.Redirect()命令将处理程序连接到我的网站的其余部分:
Response.Redirect("ImageProvider.ashx");
我的问题是 - 在调用泛型处理程序时,如何传递任何类型的变量参数(sql查询中的XXX)?
非常感谢
答案 0 :(得分:2)
使用查询字符串。
在ProcessRequest中:
var Id = context.Request.QueryString["Id"];
用法:
Response.Redirect("ImageProvider.ashx?Id=100");
答案 1 :(得分:0)
HttpContext.Request.QueryString
或HttpContext.Request.Form
接受来自HTTP请求的值。SqlParameter
。切勿使用字符串连接。using()
块来确保IDisposable
对象已关闭并正确放置。像这样:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
String id = context.Request.QueryString("id");
if( String.IsNullOrEmpty( id ) )
{
context.Response.StatusCode = 404;
return;
}
using( SqlConnection c = new SqlConnection( connectionString ) )
using( SqlCommand cmd = c.CreateCommand() )
{
c.Open();
cmd.CommandText = "SELECT img FROM subjects WHERE [Id] = @id"
cmd.Parameters.Add( "@id", SqlDbType.VarChar ).Value = id;
Byte[] img = (Byte[])cmd.ExecuteScalar();
context.Response.BinaryWrite( img );
}
}