Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Products
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Integrating Google reCAPTCHA v3 in ASP.NET Core for Seamless Bot Protection

Integrating Google reCAPTCHA v3 in ASP.NET Core for Seamless Bot Protection

Date- May 25,2026 603
google recaptcha

Overview

Google reCAPTCHA v3 is a security service designed to protect websites from spam and abuse by leveraging advanced risk analysis techniques. Unlike its predecessors, reCAPTCHA v3 operates silently in the background, analyzing user interactions with the website to determine whether the traffic is legitimate or not. This approach minimizes user friction since it does not require users to solve challenges like selecting images or typing distorted text.

The primary problem reCAPTCHA v3 aims to solve is the increasing prevalence of automated bots that can perform malicious activities such as spamming forms, scraping content, or brute-forcing login credentials. By utilizing a scoring system that evaluates user behavior, reCAPTCHA v3 provides developers a way to filter out potentially harmful interactions while allowing genuine users to navigate the site seamlessly. Real-world use cases include contact forms, login pages, and comment sections where user validation is crucial to maintaining site integrity.

Prerequisites

  • ASP.NET Core knowledge: Familiarity with creating and running ASP.NET Core applications.
  • Google Account: Required to register your site and obtain the reCAPTCHA API keys.
  • Basic HTML and JavaScript: Understanding how to integrate JavaScript libraries into your web pages.
  • NuGet Package Manager: Knowledge of managing packages in ASP.NET Core to install necessary libraries.

Setting Up Google reCAPTCHA v3

Before integrating reCAPTCHA v3 into your ASP.NET Core application, you must set up an account with Google to obtain the necessary API keys. This process involves registering your domain and selecting reCAPTCHA v3 as the service type. The generated keys will allow your application to communicate securely with Google's servers.

To get started, visit the Google reCAPTCHA website. After logging in, navigate to the Admin Console and register a new site. You will need to provide your domain name and select reCAPTCHA v3. Once registered, you will receive a Site Key and a Secret Key, which are essential for the integration process.

// Example of registering reCAPTCHA in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddSingleton<IConfiguration>(Configuration);
}

The code above demonstrates how to add configuration services in the Startup.cs file. The reCAPTCHA service can be registered as a singleton, allowing it to be injected where needed throughout the application.

Registering reCAPTCHA in Configuration

Once you have the keys, you should store them in your application's configuration settings (e.g., appsettings.json) for easy access. This practice helps maintain security and keeps sensitive information out of your source code.

{
  "ReCaptcha": {
    "SiteKey": "YOUR_SITE_KEY",
    "SecretKey": "YOUR_SECRET_KEY"
  }
}

In this JSON configuration, replace YOUR_SITE_KEY and YOUR_SECRET_KEY with the actual keys obtained from Google. This configuration allows your application to retrieve the keys easily when needed.

Integrating reCAPTCHA v3 in Forms

To implement reCAPTCHA v3 in your forms, you need to include the reCAPTCHA API script in your HTML and modify the form submission logic to include the reCAPTCHA token. This token is generated based on user interactions with the page and is sent to the server for validation.

// In your Razor page or view
@page
@model YourNamespace.YourModel




    


    

This code includes the reCAPTCHA JavaScript API and executes it when the page is ready. The generated token is appended to the form as a hidden input field named g-recaptcha-response, which will be sent to the server upon form submission.

Server-Side Verification of the reCAPTCHA Token

After the form is submitted, the server must validate the token with Google's reCAPTCHA API to ensure it is legitimate. This involves making an HTTP POST request to Google's verification endpoint with the token and your secret key.

public async Task OnPostAsync()
{
    var token = Request.Form["g-recaptcha-response"];
    var secretKey = Configuration["ReCaptcha:SecretKey"];

    using (var client = new HttpClient())
    {
        var response = await client.PostAsync($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={token}", null);
        var jsonResponse = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<ReCaptchaResponse>(jsonResponse);

        if (result.Success)
        {
            // Handle successful verification
        }
        else
        {
            // Handle verification failure
        }
    }
}

This code snippet shows how to verify the reCAPTCHA token on the server side. The verification process involves sending a request to the reCAPTCHA API endpoint with the secret key and the user's token. The response is then deserialized to check if the verification was successful.

Edge Cases & Gotchas

While integrating reCAPTCHA v3, developers might encounter several pitfalls that can lead to misconfigurations or security vulnerabilities. One common issue is not validating the reCAPTCHA response correctly, which can allow bots to bypass the protection.

// Incorrect handling of verification
if (!result.Success || result.Score < 0.5)
{
    // Failed verification logic
}

The above code snippet demonstrates an incorrect approach by only checking the Success property without considering the Score. A low score indicates high risk, and failing to implement this check can lead to security vulnerabilities.

Common Mistakes

  • Not using HTTPS: Always serve your site over HTTPS when using reCAPTCHA to ensure secure transmission of token data.
  • Hardcoding API keys: Never hardcode your reCAPTCHA keys in your source code. Always retrieve them from a configuration file or environment variables.
  • Ignoring the score: Failing to check the score returned by reCAPTCHA can result in approving malicious requests.

Performance & Best Practices

Implementing reCAPTCHA v3 should not significantly degrade your web application's performance. However, there are several best practices to follow to optimize its usage. First, ensure that the reCAPTCHA API is only loaded on pages that require protection. This prevents unnecessary overhead on pages without forms.

Utilizing caching strategies can also enhance performance. For example, if your application has high traffic, consider caching the responses from the reCAPTCHA API to minimize the number of requests made to Google. This can be achieved using in-memory caching or distributed caching solutions.

Measurable Tips

  • Measure the impact of reCAPTCHA on your loading times using tools like Google PageSpeed Insights.
  • Monitor the number of successful vs. failed verifications to gauge the effectiveness of your implementation.
  • Regularly review and update your reCAPTCHA keys to ensure optimal security.

Real-World Scenario: Building a Contact Form

In this section, we will tie all the concepts together by creating a simple contact form that utilizes reCAPTCHA v3 for validation. This form will include fields for the user's name, email, and message, and will require the reCAPTCHA token for submission.

@page
@model YourNamespace.ContactModel




    


    
public async Task OnPostAsync() { var token = Request.Form["g-recaptcha-response"]; var secretKey = Configuration["ReCaptcha:SecretKey"]; using (var client = new HttpClient()) { var response = await client.PostAsync($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={token}", null); var jsonResponse = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<ReCaptchaResponse>(jsonResponse); if (result.Success && result.Score >= 0.5) { // Handle successful contact form submission } else { // Handle verification failure } } }

This complete contact form example integrates reCAPTCHA v3 by executing the API call, capturing the token, and validating it on the server. The integration ensures that only legitimate submissions are processed, providing a secure and user-friendly experience.

Conclusion

  • Google reCAPTCHA v3 provides a powerful way to protect applications from bots without hindering user experience.
  • Proper setup and verification of reCAPTCHA tokens are crucial for maintaining security.
  • Best practices, including caching and performance monitoring, can optimize the integration.
  • Real-world implementations demonstrate the practical application of reCAPTCHA v3 in common scenarios.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Integrating Cloudflare Turnstile in ASP.NET Core: A Privacy-First CAPTCHA Alternative
May 26, 2026
Integrating Google OAuth 2.0 Login in ASP.NET Core: A Comprehensive Guide
Apr 29, 2026
Integrating Slack API in ASP.NET Core: Building Bots, Webhooks, and Notifications
May 24, 2026
Reddit API Integration in ASP.NET Core: Handling Posts, Subreddits, and OAuth Authentication
May 24, 2026
Previous in ASP.NET Core
Integrating Discord Bots with ASP.NET Core Using Discord.NET Libr…
Next in ASP.NET Core
Integrating Have I Been Pwned API in ASP.NET Core for Password Br…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    CWE-269: Improper Privilege Management - Implementing the … 328 views
  • 2
    Building Custom Bedrock Add-Ons with JavaScript: A Complet… 1,928 views
  • 3
    Elasticsearch Integration in ASP.NET Core - Full-Text Sear… 240 views
  • 4
    Error-An error occurred while processing your request in .… 11,953 views
  • 5
    Fix Gemini API Error 429: Quota Exceeded on Free Tier (Sys… 815 views
  • 6
    Send Email With HTML Template And PDF Using ASP.Net C# 17,168 views
  • 7
    Integrating Google reCAPTCHA Validation in ASP.NET MVC 6,456 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26677 views
  • Exception Handling Asp.Net Core 21714 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 21166 views
  • How to implement Paypal in Asp.Net Core 20126 views
  • Task Scheduler in Asp.Net core 18195 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1780
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Products
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor