Thursday, May 4, 2017

Recapatcha - Http Client POST Example


           #region Google keys
            /*  Site Key  #Your HASH
                Secret Key #SOME HASH
            */
            #endregion
            var serviceURL = ConfigurationManager.AppSettings["RecaptchaUrl"];
            var secret = ConfigurationManager.AppSettings["RecaptchaSecret"];
          
            var client = new HttpClient();
            try
            {
                var values = new List<KeyValuePair<string, string>>();

                //Add values to data for post
                values.Add(new KeyValuePair<string, string>("secret", secret));
                values.Add(new KeyValuePair<string, string>("response", captchaResult.Get("g-recaptcha-response")));
                FormUrlEncodedContent content = new FormUrlEncodedContent(values);

                // Post the data
                var dataResult = client.PostAsync(serviceURL, content).Result;
                var responseJson = dataResult.Content.ReadAsAsync<CaptchaResponseJson>();

                // Acess content as stream which you can read into some string
                //Console.WriteLine(dataResult.Content);

                //Access the result status code
                _logger.Log(Level.Error,dataResult.StatusCode.ToString());
                
                return responseJson.Result.success.ToLower().Equals("true");
            }
            catch (AggregateException ex)
            {
                //get all possible exceptions which are thrown
                foreach (var item in ex.Flatten().InnerExceptions)
                {
                    _logger.Log(Level.Error, item.Message);
                }
            }

            return false;