在 MVC 应用程序中使用 C# 的 ReCaptcha 帖子

本文关键字:ReCaptcha 帖子 MVC 应用程序 | 更新日期: 2023-09-27 18:33:26

我正在尝试使用此代码直接向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;
        }
    }

在 MVC 应用程序中使用 C# 的 ReCaptcha 帖子

IF/ELSE 中的"return"意味着无法访问"清理流"代码,并且由于 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;
}

我想你需要删除帖子数据上的?

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

 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();
        }
    }

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

 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;
 }