2014-12-11 84 views
2

如何在Windows Phone上顯示Recaptcha?Recaptcha和Windows Phone

我在後端使用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; 
     } 
    } 
} 

回答

0

這種方法獲取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}" />