Introduction
The code snippets below show how to use a simple class to create a validation mechanism via captcha in ASP.NET, using Jquery and MVC.
Using the Code
The code consists of two parts that work together to make the code work.
The first is JavaScript that runs on the client and should be placed on the page header. It is responsible for making the request to the server.
Note: I must remember that this JavaScript code requires Jquery, which can be downloaded here.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
loadCaptcha();
});
function loadCaptcha() {
$.ajax({
type: 'GET', url: 'Home/generateCaptcha',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) { $("#m_imgCaptcha").attr('src', data); },
error: function (data) { alert("Error while loading captcha image") }
});
}
</script>
The second is C# runs on the server. That receives the request from the page, generates an image with the specified text. This text can be generated by a function embedded in class or can be specified by the developer. The text is saved in the Session
and is used to validate the data entered by the user.
public ActionResult generateCaptcha()
{
System.Drawing.FontFamily family = new System.Drawing.FontFamily("Arial");
CaptchaImage img = new CaptchaImage(150, 50, family);
string text = img.CreateRandomText(4) + " " + img.CreateRandomText(3);
img.SetText(text);
img.GenerateImage();
img.Image.Save(Server.MapPath("~") +
this.Session.SessionID.ToString() + ".png",
System.Drawing.Imaging.ImageFormat.Png);
Session["captchaText"] = text;
return Json(this.Session.SessionID.ToString() + ".png?t=" +
DateTime.Now.Ticks, JsonRequestBehavior.AllowGet);
}
Here is an example of a captcha image generated using this code:
Advantages of Use
- You know what's running on your server.
- No special settings are needed.
- It is not necessary use third party components that can fail.
- It is fully customizable.