Thursday, February 24, 2011

Returning a Captcha Image as a Result from ASP.NET MVC

Recently I was trying to generate a simple Captcha for ASP.NET MVC. I looked at MVC ReCaptcha, which is a great tool, but I didn't want a confusing ReCaptcha for simple form validation. My goal was to use something very simple to prevent SPAM, but at the same time provide a seamless enough experience to not scare off human users.

Next, I came across this article - Simple CAPTCHA, Create your own in C#. It provides an excellent example on how to generate a simple Captcha. My next task was to convert this to ASP.NET MVC code (I used ASP.NET MVC 3.0). Documentation on this might be a little confusing, but the process ended up extremely simple.

The key that I learned here, is that you need to return FileContentResult. Initially I tried returning FileResult with no success.

    public class CaptchaController : Controller
    {
        public ActionResult GetCaptcha()
        {
             var captcha = GetCaptchaImage();
             var result = new FileContentResult(captcha, "image/png");
             result.FileDownloadName = "captcha.png"; // optional
             return result;
         }
         
         
          private Byte[] GetCaptchaImage()
          {
             // Code to generate your Captcha
             // I used the logic from Raymund Macaalay's blog
             // linked above
             ... 

             var oBytes = oMemoryStream.GetBuffer();
             oMemoryStream.Close();
             oMemoryStream.Dispose();
           
             return oBytes;
         }
}

Once you have this code, you can reference your image from views:

        <img src="/Captcha/GetCaptcha/anything_you_want.png" />

One more thing to note, you can put any file name at the end. This part gets completely ignored by your controller (unless you modify it to take a parameter and do something with it). And that's it!

0 comments:

Post a Comment