Skip to content

Getting started

Paul Biccherai edited this page May 24, 2017 · 11 revisions

Getting started

Get an API key

First you need to get an API key from google at https://www.google.com/recaptcha/admin and you can refer to https://developers.google.com/recaptcha/intro for more documentation about reCAPTCHA.

Install the package

Using the package manager console in visual studio run "Install-Package PaulMiami.AspNetCore.Mvc.Recaptcha"
or
By adding the package directly to your "project.json" file:

    "dependencies": {
        ...
        "PaulMiami.AspNetCore.Mvc.Recaptcha": "1.1.1"
        ...
     }

and run "dotnet restore" in the console.

Configure the service

In your "Startup" class add the "RecaptchaService" in the "ConfigureServices" method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddRecaptcha(new RecaptchaOptions
        {
            SiteKey = Configuration["Recaptcha:SiteKey"],
            SecretKey = Configuration["Recaptcha:SecretKey"]
        });
    }

The "SiteKey" and "SecretKey" are required (you get those from your google admin console).
For development I recommend that you use the user secrets configuration extension to store those settings to avoid committing them to source control.

Using the control

The control is a TagHelper, so the first thing you need to do is include the TagHelpers from this package in your "_viewImport.cshtml" file.

    @addTagHelper *, PaulMiami.AspNetCore.Mvc.Recaptcha

Then you can just add the TagHelper to place the reCAPTCHA control

    <recaptcha/>

and in your script section

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    <recaptcha-script/>

The TagHelper "recaptcha-script" is required, it adds the script reference for the control, out of the box it integrated with jquery validation and need to be place just after those scripts. You can disable jquery validation if you want to like this:

    <recaptcha-script jquery-validation="false" />

Validating the reCaptcha response in your controller

Apply the "ValidateRecaptcha" attribute on your action and check if the "ModelState" is valid.

[ValidateRecaptcha]
[HttpPost]
public IActionResult Index(YourViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        return new OkResult();
    }

    return View();
}

Example

Look at https://github.com/PaulMiami/reCAPTCHA/tree/master/sample/TestWebApp for a simple example.