Click here to Skip to main content
14,661,507 members
Articles » Web Development » Validation » General
Posted 10 Jan 2012


152 bookmarked

ASP.NET MVC - reCAPTCHA and Email Confirmation

Rate this:
4.98 (60 votes)
Please Sign up or sign in to vote.
4.98 (60 votes)
25 Mar 2013Ms-PL
How to add reCAPTCHA and email confirmation to your ASP.NET MVC site.


ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enable a clean separation of concerns and that gives you full control over markup for enjoyable, agile development.

ASP.NET MVC includes many features that enable fast, TDD-friendly development for creating sophisticated applications that use the latest web standards.

You can also choose an existing platform based on ASP.NET MVC from Microsoft Gallery, from:

  • Blogs
  • CMS
  • eCommerce
  • Forums
  • Galleries
  • Wiki
  • And more

But one thing that you probably need to add to any Web Application is BOTS Protection and Email Integrity.

So how can you prevent abuse from "bots", automated programs usually written to generate spam, and how to make sure the user has given you his real email address when registering on your Web Application?

The answer is: reCAPTCHA and Email Confirmation



A CAPTCHA is a program that can tell whether its user is a human or a computer. You've probably seen them — colorful images with distorted text at the bottom of Web registration forms. CAPTCHAs are used by many websites to prevent abuse from "bots," or automated programs usually written to generate spam. No computer program can read distorted text as well as humans can, so bots cannot navigate sites protected by CAPTCHAs.

Step 1: Download and Get reCAPTCHA Keys

First go to the reCAPTCHA site and register for a unique key, then Download reCAPTCHA .NET Library.

Save your Public and Private keys safely.


Step 2: Create ASP.NET MVC 3 Web Application

Now, let’s start a new ASP.NET MVC 3 Web Application Project in Visual Studio 2010.


Choose to create from “Internet Application” template


Step 3: Recaptcha

Add the Recaptcha DLL as a reference to your project.


Modify site Web.config with new keys under the appSettings section and add the keys we received before.

  • ReCaptchaPrivateKey
  • ReCaptchaPublicKey


Step 4: Change Registration

Open the Controllers folder, open the AccountController file, and locate the Register method, add the new attribute:



And add the reCAPTCHA logic to your registration code:

public ActionResult Register(RegisterModel model, bool captchaValid)
    if (!captchaValid)
        ModelState.AddModelError("", "You did not type the verification 
                                    word correctly. Please try again.");
        if (ModelState.IsValid)
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, 
                                  model.Email, null, null, true, null, 
                                  out createStatus);
            if (createStatus == MembershipCreateStatus.Success)
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return RedirectToAction("Index", "Home");
    // If we got this far, something failed, redisplay form
    return View(model);

Now place the following command in the Register.cshtml file:



Run your web site and enter the registration page, now you have to enter captcha before compiling the registration.


Email Confirmation

In order to make sure the user has gave you his real email you need to use Email Confirmation mechanism to your site.

ASP MVC is doing some of the work for us, when a user is register to your site is assign with a unique ID (GUID) property called - ProviderUserKey

I’ll use this value to verify the account.

Step 1: Modify Web.Config with SMTP Settings

Before we get started with the Email Confirmation implementation we need to define our email settings, to do so I’ve used my Gmail account (just for this test) and add those values in the web.config just below the configuration tag.

      <smtp deliveryMethod="Network">
        <network host="" port="587" 


                                       password="[Your Password]" />

Step 2: Add Confirmation View

After the user has register we want to redirect him to a confirmation page and tell him to check his email for the confirmation link, so:

Add a new View called – Confirmation

    ViewBag.Title = "Email Confirmation";
    Thank you for registering. Please check your email for a confirmation
    request with a link that will confirm your account. Once you click the
    link, your registration will be complete.</p> 

In the AccountController add the result for confirmation.

public ActionResult Confirmation()
    return View();

Step 3: Send Mail

Before changing the registration we need to create the email functionality, this confirmation email will contain the ProviderUserKey and a direct link to our site.

The SendConfirmationEmail method will receive the UserName, and using Membership.GetUser we’ll be able to get all the information on that user and of course the ProviderUserKey.

I’ve built the confirmation URL using HttpContext and combined the User Guid ID and the site.

 var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart 
(UriPartial.Authority) + "/Account/Verify/" + confirmationGuid; 
public class EmailManager
    private const string EmailFrom = "";
    public static void SendConfirmationEmail(string userName)
        var user = Membership.GetUser(userName.ToString());
        var confirmationGuid = user.ProviderUserKey.ToString();
        var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart
           (UriPartial.Authority) + "/Account/Verify/" + confirmationGuid;
        using (var client = new SmtpClient())
            using (var message = new MailMessage(EmailFrom, user.Email))
                message.Subject = "Please Verify your Account";
                message.Body = "<html><head><meta content=\"text/html; 
                charset=utf-8\" /></head><body><p>Dear " + user.UserName +
                   ", </p><p>To verify your account, please click the following link:</p>"
                   + "<p><a href=\"" + verifyUrl + "\" target=\"_blank\">" + verifyUrl + "
                   +"</a></p><div>Best regards,</div><div>Someone</div><p>Do not forward "
                   +"this email. The verify link is private.</p></body></html>";
                message.IsBodyHtml = true;
                client.EnableSsl = true;

Step 4: Change Registration

Now we need to change the Registration functionality. The main thing is when creating a new user we need to change the user state to Not Approve and instead of performing login, we need to send him an email using our EmailManager and show him the confirmation page.

public ActionResult Register(RegisterModel model)
    if (ModelState.IsValid)
        // Attempt to register the user
        MembershipCreateStatus createStatus;
        //Make sure the user is not approve at this point!!!
        Membership.CreateUser(model.UserName, model.Password, model.Email,
        null, null, false, null, out createStatus);
        if (createStatus == MembershipCreateStatus.Success)
            return RedirectToAction("Confirmation", "Account");
            ModelState.AddModelError("", ErrorCodeToString(createStatus));
    // If we got this far, something failed, redisplay form
    return View(model);

Step 5: Add Verify

In AccountController I’ve added a Verify ActionResult. Verify will receive the User ID, then we’ll check for some bad IDs, if the user is already approved SignOut the user and redirect to the LogOn page, if the user is not approved, we need to change IsApprove to true and call UpdateUser to update the database with the new changes, also we will do the login for the user and redirect him to the home page.

public ActionResult Verify(string id)
    if (string.IsNullOrEmpty(id) || (!Regex.IsMatch(id, @"[0-9a-f]{8}\-
        ViewBag.Msg = "Not Good!!!";
        return View();
        var user = Membership.GetUser(new Guid(id));
        if (!user.IsApproved)
            user.IsApproved = true;
            FormsAuthentication.SetAuthCookie(user.UserName, false);
            return RedirectToAction("Index", "Home");
            ViewBag.Msg = "Account Already Approved";
            return RedirectToAction("LogOn");




This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


About the Author

Shai Raiten
Architect Sela
Israel Israel
Shai Raiten is VS ALM MVP, currently working for Sela Group as a ALM senior consultant and trainer specializes in Microsoft technologies especially Team System and .NET technology. He is currently consulting in various enterprises in Israel, planning and analysis Load and performance problems using Team System, building Team System customizations and adjusts ALM processes for enterprises. Shai is known as one of the top Team System experts in Israel. He conducts lectures and workshops for developers\QA and enterprises who want to specialize in Team System.

My Blog:

Comments and Discussions

QuestionAwesome Pin
Ernesto Amable21-Sep-15 5:13
MemberErnesto Amable21-Sep-15 5:13 
QuestionThanks ............................. Pin
borzadaran22-Jul-15 21:23
Memberborzadaran22-Jul-15 21:23 
QuestionVerify(string id) -getting Id but its Regex failing... Pin
dsmportal18-Sep-13 4:17
Memberdsmportal18-Sep-13 4:17 
AnswerRe: Verify(string id) -getting Id but its Regex failing... Pin
Member 103092096-Nov-13 5:44
professionalMember 103092096-Nov-13 5:44 
QuestionModify Custom membership method Pin
wasfasheikh16-Aug-13 2:38
Memberwasfasheikh16-Aug-13 2:38 
QuestionExcellent helped me in umbraco mvc web app Pin
Harsh Baid19-Jul-13 1:31
professionalHarsh Baid19-Jul-13 1:31 
GeneralMy vote of 5 Pin
M Rayhan27-May-13 1:47
MemberM Rayhan27-May-13 1:47 
GeneralMy vote of 5 Pin
csharpbd11-Apr-13 22:14
professionalcsharpbd11-Apr-13 22:14 
GeneralRe: My vote of 5 Pin
Shai Raiten11-Apr-13 23:26
MemberShai Raiten11-Apr-13 23:26 
SuggestionI don't have the Html.GenerateCaptcha() method Pin
sinmas20-Nov-12 7:47
Membersinmas20-Nov-12 7:47 
GeneralRe: I don't have the Html.GenerateCaptcha() method Pin
Rock Bolton6-Jan-14 16:08
MemberRock Bolton6-Jan-14 16:08 
GeneralMy vote of 5 Pin
Mallikarjun4u29-Oct-12 5:55
MemberMallikarjun4u29-Oct-12 5:55 
GeneralRe: My vote of 5 Pin
Shai Raiten11-Apr-13 23:26
MemberShai Raiten11-Apr-13 23:26 
GeneralMy Vote 5 Pin
Sergey Morenko28-Jul-12 6:05
professionalSergey Morenko28-Jul-12 6:05 
GeneralRe: My Vote 5 Pin
Shai Raiten11-Apr-13 23:25
MemberShai Raiten11-Apr-13 23:25 
QuestionAbout article Pin
006ashish13-Jun-12 20:05
Member006ashish13-Jun-12 20:05 
AnswerRe: About article Pin
Tomasz Sikora1-Oct-12 8:18
MemberTomasz Sikora1-Oct-12 8:18 
GeneralMy vote of 5 Pin
JF201521-May-12 23:00
MemberJF201521-May-12 23:00 
QuestionJust tried on 4.5 Visual Studio 11 Beta - works amazing! Vote 5 Pin
Member 80030639-May-12 4:08
MemberMember 80030639-May-12 4:08 
QuestionPLEASE HELP ! Pin
Yasser Youssef15-Apr-12 23:47
MemberYasser Youssef15-Apr-12 23:47 
QuestionActionResult Verify(string id) -- id is null Pin
jeff00seattle29-Mar-12 12:07
Memberjeff00seattle29-Mar-12 12:07 
AnswerRe: ActionResult Verify(string id) -- requires [HttpGet] Pin
jeff00seattle29-Mar-12 12:31
Memberjeff00seattle29-Mar-12 12:31 
QuestionNice artice Pin
GamersWanted5-Mar-12 9:01
MemberGamersWanted5-Mar-12 9:01 
AnswerRe: Nice artice Pin
Shai Raiten22-Mar-12 21:35
MemberShai Raiten22-Mar-12 21:35 
QuestionMy vote of 5 Pin
Ganesan Senthilvel25-Feb-12 17:23
MemberGanesan Senthilvel25-Feb-12 17:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.