views:

32

answers:

2

I'm implementing the recaptcha control from google.

I built a simple c# test project from their example and all works. Now, instead of having the PublicKey and PrivateKey in the aspx page, I'd rather assign these values at run time as they will most likely be pulled from either the web.config or a database table.

I tried the following in the Page_Load

    protected void Page_Load(object sender, EventArgs e) {
        recaptcha.PublicKey = "<deleted for obvious reasons>";
        recaptcha.PrivateKey = "<ditto>";
    }

but I get an error stating "reCAPTCHA needs to be configured with a public & private key."

I also tried overriding the oninit method of the page and assigning the values there, but no joy.

Any ideas on where this needs to go?

+1  A: 

Try using the value of setincodebehind in your tag, like this:

<recaptcha:RecaptchaControl ID="myRecaptcha" runat="server" 
  PublicKey="setincodebehind" PrivateKey="setincodebehind" ... />

That should let you set the keys in the codebehind properly. There are a couple of other ways to do it as well. For example, you can get the values from a static class like this:

<recaptcha:RecaptchaControl ID="myRecaptcha" runat="server" 
  PublicKey="<%= RecaptchaSettings.PublicKey %>" 
  PrivateKey="<%= RecaptchaSettings.PrivateKey %>" ... />

Where RecaptchaSettings is a class you provide. Or, you could put the keys into an appSettings section of your web.config, and access them like this:

<recaptcha:RecaptchaControl ID="myRecaptcha" runat="server" 
  PublicKey="<%$appSettings:RecaptchaPublicKey %>" 
  PrivateKey="<%$appSettings:RecaptchaPrivateKey %>" ... />

Hope that helps.

mjd79
Perfect. Thanks
Chris Lively
+1  A: 

Another way to set key values, use <appSettings> keys RecaptchaPublicKey and RecaptchaPrivateKey. These values will be used automatically unless it is overridden during control declaration (mjd79's answer, first way).

Pro: if you have multiple declaration, you only need to keep the keys in one place, DRY principle.

This behaviour can be seen through the source code, RecaptchaControl.cs, line 135-...:

public RecaptchaControl()
{
    this.publicKey = ConfigurationManager.AppSettings["RecaptchaPublicKey"];
    this.privateKey = ConfigurationManager.AppSettings["RecaptchaPrivateKey"];
    ...
Adrian Godong
Interesting find. Thanks!
Chris Lively