tanveery / recaptcha-net

reCAPTCHA for .NET library lets you easily use Google's reCAPTCHA in an ASP.NET Web Forms / MVC / ASP.NET Core application.
Apache License 2.0
161 stars 68 forks source link

reCaptcha - Asp.Net 3.1 - Site key cannot be null or empty #67

Open Dickovski opened 2 years ago

Dickovski commented 2 years ago

I have two websites, installed reCaptcba on one, created the keys in Google and followed the guidance, putting the keys in web.config and appsettings.json (probably not necessary). This works fine, I even found the keys that allow it to be tested on a local server. I then went to my second website and tried to do the same. This website had no web.config file so I created one and put the keys for the second website into it. However, when I tested the site on the local server it came up with the error 'InvalidOperationException: Site key cannot be null or empty.' when it hits the line @Html.RecaptchaWidget(). I then published the website and the same error occurred. I suspect that web.config is not be accessed, although it is there in both my local View folder and on the remote server. Assuming that this is where the problem lies, how do I get the key read?

TuTAH1 commented 2 years ago

Have you tried to debug the line like var test = Configuration["RecaptchaSiteKey"];? If it doesn't loads, use this code, maybe it will work for you:

public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();

// In Startup.cs

public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
        {
            RecaptchaConfigurationManager.SetConfiguration(Configuration.GetSection("SectionName")); 
        }

and app settings are something like

{
  "SectionName": {
        "RecaptchaSiteKey": "yourkey",
        "RecaptchaSecretKey": "yourkey"
  }
}

My mistake was that I put the whole Configuration in the RecaptchaConfigurationManager (not just a section), that's why it wasn't working for me.