/
ReCaptchaGenerator.cs
48 lines (41 loc) · 1.66 KB
/
ReCaptchaGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Recaptcha;
namespace PoliteCaptcha
{
public class ReCaptchaGenerator : ICaptchaGenerator
{
public IHtmlString Generate(HtmlHelper htmlHelper)
{
if (htmlHelper == null)
throw new ArgumentNullException("htmlHelper");
var publicApiKey = ConfigurationManager.AppSettings[Const.ReCaptchaPublicKeyAppSettingKey];
if (publicApiKey == null)
{
if (!htmlHelper.ViewContext.HttpContext.Request.IsLocal)
throw new InvalidOperationException(ErrorMessage.DefaultReCaptchApiKeysOnlyAllowedForLocalRequest);
publicApiKey = Const.ReCaptchaLocalhostPublicKey;
}
var privateApiKey = ConfigurationManager.AppSettings[Const.ReCaptchaPrivateKeyAppSettingKey];
if (privateApiKey == null)
{
if (!htmlHelper.ViewContext.HttpContext.Request.IsLocal)
throw new InvalidOperationException(ErrorMessage.DefaultReCaptchApiKeysOnlyAllowedForLocalRequest);
privateApiKey = Const.ReCaptchaLocalhostPrivateKey;
}
var recaptchaControl = new RecaptchaControl
{
ID = Const.ReCaptchControlId,
PublicKey = publicApiKey,
PrivateKey = privateApiKey,
};
var htmlWriter = new HtmlTextWriter(new StringWriter());
recaptchaControl.RenderControl(htmlWriter);
return new MvcHtmlString(htmlWriter.InnerWriter.ToString());
}
}
}