Creating Captcha HTML Helper
After working with ASP.Net MVC, and my previous posts, in this Post I am trying to implement a Captcha HTML Helper, an HTML Helper is just a method that returns a string. Creating Custom HTML Helpers. It is an extension method, to the existing HTML Helper class.
Here is code.(For more details about the Captcha generation code, check my previous post. : Captcha using ASP.Net and C#);
public static class CaptchaHelper
{
public static string Captcha(this HtmlHelper helper, string text)
{
string srcPath = System.Web.VirtualPathUtility.ToAbsolute("~/Handler1.ashx");
string htmlContent = string.Empty;
htmlContent += "<script type=\"text/javascript\">function __rc(){document.getElementById(\"" + text +
"\").src = \"../Handler1.ashx?query=\" + Math.random();}</script>";
htmlContent += string.Format("<img id=\"{0}\" src=\"{1}\" alt=\"Captcha Image\"/>", text, srcPath);
htmlContent += "<a href=\"#\" onclick=\"javascript:__rc();\">Reset</a>";
return htmlContent;
}
}
And in the View you can use like, you may need to import the Namespace of CaptchaHelper class.
< %= Html.Captcha("Sample") %>
It will render a security image. Happy Programming
How to use Session objects in an HttpHandler
In my previous post, Captcha using ASP.Net and C#, you may noticed that I am not talking about how can I validate the user is entering correct value or not. I thought of using Sessions for this purpose, like in the HTTP Handler, I wrote some code like
context.Session["captcha"] = drawString;
But that code failed, by throwing a Null Reference exception. After debugging I found the session object is coming as NULL. Then after doing a little search I found a nice post about how can we use session state in Http Handlers. For this you have to implement an empty interface, IRequiresSessionState, which in the available in the System.Web.SessionState namespace, you have to add reference of this namespace in your code, implement the interface, and you can use session in the Http Handler.
using System.Web.SessionState;
public class Handler : IHttpHandler, IRequiresSessionState
{
//Your implementation.
}
You can also use IReadOnlySessionState interface instead of IRequiresSessionState, which gives read only access to the session objects.
Now you can save the drawString value to the session state and in the C# code, you can read it from session and check with the user entry.
You can get more details from this post :How to use Session values in an HttpHandler
Captcha using ASP.Net and C#
Few days back, I got some question related to Captcha (security mechanism, which helps web masters to avoid spam) in a Forum. So I thought of implementing one. I got few nice scripts in Code Project, its a simple implementation, no too much logic and not too complex to understand. Also I am using an HTTP Handler instead of ASPX Page, for the implementation.
using (Bitmap b = new Bitmap(150, 40, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(b))
{
Rectangle rect = new Rectangle(0, 0, 149, 39);
g.FillRectangle(Brushes.White, rect);
// Create string to draw.
Random r = new Random();
int startIndex = r.Next(1, 5);
int length = r.Next(5, 10);
String drawString = Guid.NewGuid().ToString().Replace("-", "0").Substring(startIndex, length);
// Create font and brush.
Font drawFont = new Font("Arial", 16, FontStyle.Italic | FontStyle.Strikeout);
using (SolidBrush drawBrush = new SolidBrush(Color.Black))
{
// Create point for upper-left corner of drawing.
PointF drawPoint = new PointF(15, 10);
// Draw string to screen.
g.DrawRectangle(new Pen(Color.Red, 0), rect);
g.DrawString(drawString, drawFont, drawBrush, drawPoint);
}
b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
context.Response.ContentType = "image/jpeg";
context.Response.End();
}
}
I wrote the code in the Process Request event in HTTPHandler.
And to use this in your pages you can create an IMG tag with src attribute pointing to this.
<img src="myhandler.ashx" />
Note: Some time ASP.Net caches the image, so you may need to pass some GUID as querystring in the Handler.
Update: Sometime we may need to refresh the Captcha image, without post back, here is a simple javascript which will refresh the captcha image without post back.
<script type="text/javascript">
function RefreshCaptcha() {
var img = document.getElementById("imgCaptcha");
img.src = "Handler.ashx?query=" + Math.random();
}
</script>
<div>
<img src="Handler.ashx" id="imgCaptcha" />
<a href="#" onclick="javascript:RefreshCaptcha();">Refresh</a>
</div>
Here is the screenshot of web page using Captcha.
