Search code examples
c#asp.netgeneric-handler

Pass argument to Generic Handler in C#


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


Solution

  • Using querystring.

    In ProcessRequest:

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

    Usage:

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