Pass argument to Generic Handler in C#

4.2k Views Asked by At

I have a Generic Handler (.ashx) for an ASP.NET website that allows me to view an image file from the binary data stored in a SQL Server db:

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

            }

I'm currently connecting the handler to the rest of my website using a simple Response.Redirect() command:

 Response.Redirect("ImageProvider.ashx");

My question is - how do I pass any sort of variable argument (XXX in the sql query) when calling the generic handler?

Many thanks

2

There are 2 best solutions below

0
Magnus On BEST ANSWER

Using querystring.

In ProcessRequest:

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

Usage:

Response.Redirect("ImageProvider.ashx?Id=100");
0
Dai On
  • Use HttpContext.Request.QueryString or HttpContext.Request.Form to accept values from HTTP requests.
  • Use a SqlParameter. Never use string concatenation.
  • Use using() blocks to ensure IDisposable objects are closed and disposed correctly.

Like so:

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