1

我正在尝试使用此代码直接向 Google 发帖。我不断收到错误消息,“无效的私钥”。我已经仔细检查了它,甚至让其他人仔细检查了它。我这样做的原因是因为我使用 javascript 和 ajax 将变量传递给这个函数。

[HttpPost]
    public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
    {
        if (captchaChallenge != null && captchaResponse != null)
        {
            string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"].ToString();
            string strParameters = "?privatekey=" + strPrivateKey +
                "&remoteip=" + HttpContext.Request.UserHostAddress.ToString() +
                "&challenge=" + captchaChallenge +
                "&response=" + captchaResponse;

            WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
            request.Method = "POST";
            string postData = strParameters;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();

            if (responseFromServer.ToString() != "true")
            {
                errorCodeList.Add(8);
                return responseFromServer + strPrivateKey;
            }
            else
            {
                return responseFromServer;
            }
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
        else
        {
            errorCodeList.Add(8);
            return null;
        }
    }
4

3 回答 3

0

IF/ELSE 中的“返回”意味着“清理流”代码无法访问,并且由于 IF 的返回将结束执行,因此可以稍微简化一下:

[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
    if (captchaChallenge != null && captchaResponse != null)
    {
        // original code, remains unchanged
        /*
          ...snipped for clarity
        */

        // Clean up the streams (relocated to make it reachable code)
        reader.Close();
        dataStream.Close();
        response.Close();

        if (responseFromServer.ToString() != "true")
        {
            errorCodeList.Add(8);
            return responseFromServer + strPrivateKey; // "IF" ends execution here
        }
        return responseFromServer; // "ELSE" ends execution here
    }
    errorCodeList.Add(8);
    return null;
}
于 2014-05-19T17:27:44.720 回答
0

我猜你需要删除?关于发布数据。

我已经为我更改了代码,这有效

 private bool ValidarCaptcha(UsuarioMV usuarioMV)
    {
        Stream dataStream = null;
        WebResponse response = null;
        StreamReader reader = null;

        try
        {
            string captchaChallenge = usuarioMV.sCaptchaChallenge;
            string captchaResponse = usuarioMV.sCaptchaResponse;
            if (captchaChallenge != null
                && captchaResponse != null)
            {
                throw new Exception("Parametros captcha nulos.");
            }
            WebRequest request = WebRequest.Create("https://www.google.com/recaptcha/api/verify");
            request.Method = "POST";

            //Solicitud
            string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["RecaptchaPrivateKey"].ToString();

            NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
            outgoingQueryString.Add("privatekey", strPrivateKey);
            outgoingQueryString.Add("remoteip", "localhost");
            outgoingQueryString.Add("challenge", captchaChallenge);
            outgoingQueryString.Add("response", captchaResponse);
            string postData = outgoingQueryString.ToString();

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            //Respuesta
            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            response = request.GetResponse();
            dataStream = response.GetResponseStream();
            reader = new StreamReader(dataStream);

            if (reader.ReadLine() != "true")
            {
                string sLinea = reader.ReadLine();
                //if the is another problem
                if (sLinea != "incorrect-captcha-sol")
                {
                    throw new Exception(sLinea);
                }

                return false;
            }
            else
            {
                return true;
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
            //Clean up the streams.
            if (reader != null)
                reader.Close();
            if (dataStream != null)
                dataStream.Close();
            if (response != null)
                response.Close();
        }
    }
于 2014-11-05T23:57:42.673 回答
0

你基本上可以这样尝试。我得到了肯定的结果!!!

 public async Task<bool> ReCaptcha(Recaptcha recaptcha)
 {
    string secretKey = "YOUR_PRIVATE_KEY";
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PostAsync(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, recaptcha.Response), null);

    if (response.IsSuccessStatusCode)
    {
        var resultString = await response.Content.ReadAsStringAsync();
        RecaptchaResponse resp = JsonConvert.DeserializeObject<RecaptchaResponse>(resultString);
        if (resp.success)
        {
             return true;
        }
     }
     return false;
 }
于 2020-02-10T13:04:13.920 回答