CGC_Codes

Validate Recaptcha

Mar 13th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Net;
  6. using System.IO;
  7. using System.Web.Mvc;
  8.  
  9. namespace WeBlog.Core {
  10.   public static class RecaptchaUtils {
  11.     public static JsonResult ValidateRecaptcha( string privateKey, string remoteip, string challenge, string response) {
  12.       string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
  13.                             privateKey, remoteip,
  14.                             challenge, response);
  15.       JsonResult result = new JsonResult();
  16.       byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
  17.  
  18.       Uri serviceUri = new Uri("http://api-verify.recaptcha.net/verify", UriKind.Absolute);
  19.       try {
  20.         HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
  21.         webRequest.ContentType = "application/x-www-form-urlencoded";
  22.         webRequest.ContentLength = postDataBuffer.Length;
  23.         webRequest.Method = "POST";
  24.        
  25.         //incase you are using a proxy server
  26.         IWebProxy proxy = WebRequest.GetSystemWebProxy();
  27.         proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
  28.         webRequest.Proxy = proxy;
  29.  
  30.         Stream requestStream = webRequest.GetRequestStream();
  31.         requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
  32.  
  33.         HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
  34.         string jsonResponse = string.Empty;
  35.  
  36.         using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
  37.           jsonResponse = sr.ReadToEnd();
  38.  
  39.         string[] tokens = jsonResponse.Split(new char[] { '\n' });
  40.         if (tokens.Length == 2) {
  41.           Boolean success = tokens[0].Equals("true", StringComparison.CurrentCulture);
  42.           result.Data = new { Success = success, Message = tokens[1] };
  43.         }
  44.         else {
  45.           result.Data = new { Success = false, Message = "Invalid response returned" };
  46.         }
  47.       }
  48.       catch (Exception ex) {
  49.         result.Data = new { Success = false, Message = ex.Message };
  50.       }
  51.  
  52.       return result;
  53.     }
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment