Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic handler not returning values

Handler is not returning image. If I remove conditional statement, handler is returning image. This is my code

public void ProcessRequest(HttpContext context)
    {
        string sid = "JUN15MBACHN001";
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        connection.Open();
        SqlCommand command = new SqlCommand("select suppassportphoto from studdetails where sregno=" + sid, connection);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        Byte[] br = (Byte[])dr[0];
        if (br.Length > 1)
        {
            context.Response.BinaryWrite((Byte[])dr[0]);
        }          
        else
        {
            string path = context.Server.MapPath("~/image/emptymalepic.jpg");
            byte[] byteArray = File.ReadAllBytes(path);
            context.Response.BinaryWrite(byteArray);
        }
        connection.Close();
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

I don't know where I'm going wrong ? Any help would be appreciated.

like image 870
joseph amalanathan Avatar asked Nov 18 '25 13:11

joseph amalanathan


1 Answers

First of all i'd recommend to cast in a different way because your code might cause a invalid cast exception:

Byte[] br = dr[0] as Byte[];

Then check for null

if (br != null && br.Length > 1)

Then write the file:

context.Response.ContentType = "image/jpeg"; // or whatever type you're using
context.Response.BinaryWrite(br);

And replace

context.Response.End();

with

HttpContext.Current.ApplicationInstance.CompleteRequest();

Because i've noticed that somehow some browsers don't like the Response.End()

Hope this is usefull. Good luck!

like image 85
Clark Kent Avatar answered Nov 21 '25 02:11

Clark Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!