0

I'm trying pass some parameters to generic handler and get and image on response.

I'm using this code for image on my web page :

<a href="#"><img id="slide-3" src="~/Image_Handler.ashx?SL=/SL1&US=Kim&ID=1 alt="Tulips" title="Tulips" /></a>

When my page loads the image does not load. however, I put a button on my webpage and gave the same url to the PostBackUrl and it opens a new window and shows the picture totally OK.

Here is my Image_handler code (generic handler)

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace WEB_2._0_Programing.Private
{
/// <summary>
/// Summary description for Image_Handler
/// </summary>
public class Image_Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {

        String id;
        String Slideshow = context.Request.QueryString["SL"];
        String Username = context.Request.QueryString["US"];
        id = context.Request.QueryString["ID"];

        if (Slideshow != null)
        {
            SqlConnection connection = new SqlConnection("Data Source=KAMY-WIN7\\SQLEXPRESS;Initial Catalog=MainDataBase;Integrated Security=True;Pooling=False");

            String query = "SELECT identity(int,1,1) ID,Image into #temp FROM UserImage where (Username = @username) AND (Slideshow = @slideshow) SELECT * FROM #temp WHERE (ID=@id)";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@username", Username);
            command.Parameters.AddWithValue("@slideshow", Slideshow);
            command.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(id);
            //command.Parameters.Add("@id", SqlDbType.Int).Value = id;
            connection.Open();
            SqlDataReader dReader = command.ExecuteReader();
            dReader.Read();
            context.Response.ContentType = "image/jpeg";
            Byte[] Image = (Byte[])dReader["Image"];
            context.Response.BinaryWrite(Image);
            dReader.Close();
            connection.Close();
        }
        context.Response.Write("NOT OK!!!");

    }       

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

}

the error on this part is that on the page load context.Request.QueryString[]; doesn't return any value but when i use a button and give the same src it works fine.. Please help i have no idea what is the problem.

T F
  • 1
  • 3

1 Answers1

1

Two things:

  1. Your src attribute doesn't have a closing "
  2. You need to url encode special characters such as / in your query string.

E.g.:

<img src='~/Image_Handler.ashx?SL=<%= HttpUtility.UrlEncode("/SL1") %>&US=Kim&ID=1' />
jrummell
  • 42,637
  • 17
  • 112
  • 171