2017-07-24 33 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); 
    } 
}