While working on the AzamSharpNoSqlBlogSolution project we had the need for a Captcha control. The main purpose of the Captcha is to keep the spammers, robots posting on the site. In this article we are going to learn how to create an imageless captcha control using ASP.NET MVC framework.

The View:

The Captcha control is placed in the _addComments partial view since this view is responsible for publishing comments to the website. The control is placed in the form of HtmlHelper extension method. The view code is implemented below:

The first parameter is the name of the captcha control which in this case is "captcha". The second parameter is the strickness level. We will explain that later in the article.

Implementing Captcha Using HtmlHelper:

In order to implement the captcha control as HtmlHelper we need to extend the HtmlHelper class. This is performed by using the extension methods.

The StringBuilder is used inside the Captcha extension method and returns a string that represents hidden fields and the textbox control. The hidden fields are used to hold the randomly generated number and the textbox is for the user to input the correct answer.

The GeeklyLevel enum type sets the difficulty level of the captcha produced. Although it does not gaurentee that the captcha produced will be difficult to calculate. But you can easily fix this by providing the min and max limits on the Next method of the Random class.

Validating User Input:

When the user inputs the answer in the captcha control and submits the form the input must be validated. For this reason we implemented the CaptchaService which is responsible for validating the user input and the captcha generated parameters.

The Validate method above just makes sure that the sum of the numbers generated by the captcha control is equal to the number entered by the user.

The screenshot of the captcha control is shown below:


In this article we learned how to create a simple image less captcha control. For most web applications this will keep the spam messages away. For highly traffic websites you should use a more sophisticated captcha control.