如何在Windows Phone上显示Recaptcha?
我在后端使用Windows Phone 8.1和ASP.NET WebApi。
我的WebApi方法接受一些数据,即参数中的recaptcha-challenge和recaptcha-response。
[HttpPost]
public void Method(MyData data, string challenge, string response)
{
string recaptchaValidationUrl = "http://www.google.com/recaptcha/api/verify";
string privateKey = "MY_RECAPTCHA_PRIVATE_KEY";
if (!CheckRecaptcha(recaptchaValidationUrl, request.RcChallenge, request.RcResponse, privateKey,
HttpContext.Current.Request.UserHostAddress))
{
return new FindTechResResponse { ErrorMessage = "Invalid captcha code" };
}
}
public static bool CheckRecaptcha(string recaptchaValidationUrl, string challenge, string response, string privateKey, string clientIp)
{
using (WebClient webClient = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["privatekey"] = privateKey;
data["remoteip"] = clientIp;
data["challenge"] = challenge;
data["response"] = response;
byte[] responseBytes = webClient.UploadValues(recaptchaValidationUrl, "POST", data);
string responseString = Encoding.UTF8.GetString(responseBytes);
string isSolvedString = responseString.Split('\n')[0];
bool isSolved = bool.Parse(isSolvedString);
return isSolved;
}
}
}
最佳答案
此方法获取ChallengeId并加载图像
占位符{YOUR_PUBLIC_KEY}
应包含您的Recaptcha公钥
private async Task GetCaptcha()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.google.com/recaptcha/api/challenge?k={YOUR_PUBLIC_KEY}");
string responseStr = await response.Content.ReadAsStringAsync();
string captchure = Regex.Match(responseStr, @"challenge\s\:\s\'.+\'").Captures[0].Value;
string challenge = captchure.Split(':')[1];
challenge = challenge.Trim('\'', ' ');
string imageUrl = "http://www.google.com/recaptcha/api/image?c={0}";
response = await client.GetAsync(string.Format(imageUrl, challenge));
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
BitmapImage image = new BitmapImage();
image.SetSourceAsync(stream.AsRandomAccessStream());
CaptchaImage = image;
}
}
在XAML中,图像控件绑定到
CaptchaImage
属性<Image Source="{Binding CaptchaImage}" />