在 C# 中将参数传递给通用处理程序

Pass argument to Generic Handler in C#

我有一个 ASP.NET 网站的通用处理程序 (.ashx),它允许我从存储在 SQL 服务器数据库中的二进制数据中查看图像文件:

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)?

非常感谢

使用查询字符串。

在 ProcessRequest 中:

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

用法:

Response.Redirect("ImageProvider.ashx?Id=100");
  • 使用 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 );
    }
}