2017-07-24 17 views
0

我有一个通用的处理程序(ashx的)一个ASP.NET网站,让我从存储在SQL Server数据库二进制数据查看映像文件:传递参数的通用处理器在C#

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"); 

我的问题是 - 如何通过任何类型的变量参数(XXX在SQL查询)调用通用处理程序时?

非常感谢

+0

通常与处理程序,你会注册它反对你想让它的运行,然后从请求路径中提取数据的文件类型/路径。 –

+0

我不知道我通过注册路径和文件类型来理解你的意思。马格努斯的回答完全符合我的需求,但我很想了解更多 – Yoav24

回答

2

使用查询字符串。

在的ProcessRequest:

var Id = context.Request.QueryString["Id"]; 

用法:

Response.Redirect("ImageProvider.ashx?Id=100"); 
+0

这完美的作品,谢谢 – Yoav24

0
  • 使用HttpContext.Request.QueryStringHttpContext.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); 
    } 
} 
相关问题