This solution will demonstrate a straightforward approach in developing HTML Helper that will render the needed resources to make Google ReCaptcha 3 work in ASP.NET MVC.
Upon completing this solution, we will be able to,
  • add or reuse Google ReCaptcha 3 HTML Helpers on views and partial views
  • validate form submission without human interaction
  • let the custom attribute "ValidateReCaptcha" do the work for us
Before creating the ASP.NET MVC project, we should already have a Google ReCaptcha 3 tracking account in place. If you don't have one yet, you may sign-in at https://www.google.com/recaptcha/admin.
The following steps will walk us through the solution.
  1. Create a new ASP.NET MVC Project in Visual Studio 2017 using .NET Framework 4.6 and use a descriptive name (e.g. ReCaptcha3ASPNetMVCHelper) for your project.

  2. Compile and build your project to ensure that there are no compile-time errors.

  3. Add two new keys in <appSettings> of Web.config file - “reCaptchaSiteKey” and “reCaptchaSecretKey”. Copy and paste the following codes.
    1. <appSettings>
    2. <add key="reCaptchaSiteKey" value="site_key" />
    3. <add key="reCaptchaSecretKey" value="secret_key" />
    4. </appSettings>
  1. In the “Models” folder, add a new class and name it as “ReCaptchaForm.cs”. Copy and paste the following lines of code into that class.
    1. namespace ASPNetMVCWithReCaptcha3.Models
    2. {
    3. public class ReCaptchaForm
    4. {
    5. public string Message { get; set; }
    6. }
    7. }
  1. Under project, create a new folder “Classes” and add a new class “ReCaptcha.cs”. Copy and paste the following lines of code.
    1. using System;
    2. using System.Web;
    3. using System.Collections.Generic;
    4. using System.Web.Mvc;
    5. using System.Net.Http;
    6. using System.Configuration;
    7. namespace ASPNetMVCWithReCaptcha3.Classes
    8. {
    9. }
  1. Inside the namespace "ASPNetMVCWithReCaptcha3.Classes", add the following lines of code.
  1. Rebuild the project to ensure it is error-free.

  2. Don't forget to test the form. A successful ReCaptcha response will allow the form to submit. Otherwise, an error message will display below the message text area on the failed response.