首页 > 解决方案 > 获取 reCAPTCHA 的 JSON 响应时出现 SocketException 和 WebException

问题描述

从 reCAPTCHA 获取 JSON 响应时,出现以下异常:

SocketException (0x274c):连接尝试失败,因为连接方在一段时间后没有正确响应,或者连接失败,因为连接主机没有响应 172.217.28.228:443

WebException:无法连接到远程服务器

我的服务器端验证如下:

string secretKey = ConfigurationManager.AppSettings["Captcha.SecretKey"];
string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + response;

try
{
    using (WebClient wc = new WebClient())
    {
        string jsonResponse = wc.DownloadString(url); //The exception happens here
        CaptchaResponse captchaResponse = (new JavaScriptSerializer()).Deserialize<CaptchaResponse>(jsonResponse);

        return Convert.ToBoolean(captchaResponse.Success);
    }
}
catch (Exception ex)
{

    throw ex;
}

标签: c#asp.netrecaptcha

解决方案


在 web.config中将 useDefaultCredentials设置为 true 解决了这个问题:

<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true"/>
  </system.net>
</configuration>

推荐阅读