Written by Mark Pringle | Last Updated on Monday, November 28, 2022
MVC ASP.NET Version: 6.0 Tutorial Articles
This tutorial will show you have to implement reCaptcha in ASP.NET Core MVC and Razor pages.
What is Google reCAPTCHA?
Google reCAPTCHA is a free service that protects your website from abuse by creating challenges. This system creates challenges to help distinguish between human and automated bot access to websites.
Google reCAPTCHA Admin Console
You must register your website at the Google reCAPTCHA Admin console to use this free Google serviceGoogle reCAPTCHA Admin console. When you set up your website in the console, Google will provide you with two reCAPTCHA Keys:
- Site Key
- Secret Key
You will need to use these keys in your ASP.NET Web Application project.
Installing AspNetCore.ReCaptcha
AspNetCore.ReCaptcha is a Library for .NET Core 3.1 and .NET 5.0/6.0. Once you have aquired your two keys, you will need to install them into your web application project. You can install AspNetCore.ReCaptcha using Package Manager and the command below.
PM> Install-Package AspNetCore.ReCaptcha
After installing the AspNetCore.ReCaptcha, add your keys to the appsettings.json file.
"ReCaptcha": { "SiteKey": "enter your site key here", "SecretKey": "enter your secret key here", "Version": "v2" }
Next, you will need to inject the reCAPTCHA service into your web application. You will do that in the program.cs file using the code below.
//Add ReCaptcha builder.Services.AddReCaptcha(builder.Configuration.GetSection("ReCaptcha"));
Now you are ready to use reCAPTCHA on a Razr page.
Applying reCAPTCHA to a Razor Page
Add the following code to the top of every View where you'd like to use the reCAPTCHA service. We are going to add it to the LearnASPNET.con contact page.
@using AspNetCore.ReCaptcha
Add reCAPTCHA to your DOM using the following code.
@Html.ReCaptcha()
Add the [ValidateReCaptcha] attribute to the action method for this view. You will do this in the controller that houses this action method.
[ValidateReCaptcha] [HttpPost] public IActionResult Contact(EmailContact model) { if (ModelState.IsValid) { //Read SMTP settings from AppSettings.json. string host = this.Configuration.GetValue("EmailConfiguration:SmtpServer"); int port = this.Configuration.GetValue("EmailConfiguration:Port");
Conclusion
That's it. You have added reCaptcha to your web application. Be sure to check out the AspNetCore.ReCaptcha GitHub page.