1
public class Handler : IHttpHandler 
{

    public void ProcessRequest (HttpContext context) {
        using (Bitmap b = new Bitmap(250, 50))
        {
            Font f = new Font("Arial", 10F);
            Graphics g = Graphics.FromImage(b);
            SolidBrush whiteBrush = new SolidBrush(Color.Blue);
            SolidBrush blackBrush = new SolidBrush(Color.White);
            RectangleF canvas = new RectangleF(0, 0, 250, 50);
            g.FillRectangle(whiteBrush, canvas);
            string i = GetRandomString();
            context.Session["Captcha"] = i; // Error Msg Object reference not set to an instance of an object.
            g.DrawString(context.Session["Captcha"].ToString(), f, blackBrush, canvas);
            context.Response.ContentType = "image/gif";
            b.Save(context.Response.OutputStream, ImageFormat.Gif);
        } 
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    private string GetRandomString()
    {
        string[] arrStr = "A,B,C,D,1,2,3,4,5,6,7,8,9,0".Split(",".ToCharArray());
        string strDraw = string.Empty;
        Random r = new Random();
        for (int i = 0; i < 5; i++)
        {
            strDraw += arrStr[r.Next(0, arrStr.Length - 1)];
        }
        return strDraw;
    } 

}

Object reference not set error comes when the break pointer comes on this line:

context.Session["Captcha"] = i;
pravprab
  • 2,301
  • 3
  • 26
  • 43
user3201772
  • 79
  • 1
  • 2
  • 13

3 Answers3

1

Not all HttpHandlers provide session state. To do so, the HttpHandler must implement interfaces IRequiresSessionState or IReadOnlySessionState or both.

Sumedh
  • 58
  • 7
0

Where are you calling your ProcessRequest method? Have you created an Instance of the HttpContext and passed it as a parameter to your method?

It looks like the context variable is not properly instantiated. Thats why its showing an error on the line :

context.Session["Captcha"] = i;

Here, there is no Object Reference to the context.

Atanu Roy
  • 1,384
  • 2
  • 17
  • 29
-1

Before your Process Just Check.. I think there is no value in session..

public void ProcessRequest (HttpContext context)
 {
      if(Session["Captcha"] != null){

        //Your Code
        using (Bitmap b = new Bitmap(250, 50))
            {
                //code
            } 
        //your code over
        }
}
Shirish
  • 1,252
  • 11
  • 20
  • Implement the System.Web.SessionState.IRequiresSessionState interface: – Nikhil Chavan Feb 13 '14 at 07:35
  • @nikhil there is no need to do anything because there is only problem in session. Session["Captcha"] is null so it is causing problem no need to check and try any other thing.. – Shirish Feb 13 '14 at 09:22
  • @NikhilChavan see above edited question.. u will get ur answer...Session is null – Shirish Feb 13 '14 at 09:34