c#身份验证失败,Google ReCaptcha

时间:2018-12-10 20:20:27

标签: c# asp.net ssl-certificate httpwebrequest httpwebresponse

我试图在我的项目中包括Google ReCaptcha验证,因此在我的C#类中,有以下代码执行验证密钥的请求:

try
{
    string Response = Request["g-recaptcha-response"];

    bool Valid = false;

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
    ServicePointManager.ServerCertificateValidationCallback = delegate
    {
        return true;
    };

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create
    ("https://www.google.com/recaptcha/api/siteverify?secret=MYKEY&response=" + Response);

    using (WebResponse wResponse = req.GetResponse())
    {

        using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
        {
            string jsonResponse = readStream.ReadToEnd();

    ...
}
    }
}
catch (WebException ex)
{
    ...
}

但是我不断收到异常消息。当我包括SecurityProtocol开关时,我没想到会收到这种错误。我在这里想念什么吗?我的项目基于.NET Framework 4.5。我已经有这种错误,但是通过包含SecurityProtocol开关已解决了,但是这次没有。

  

基础连接已关闭:发送中发生意外错误。 System.IO.IOException:身份验证失败,因为远程方已关闭传输流。位于System.Net.Security.SslState处的System.Net.Security.SslState.StartReadFrame(Byte []缓冲区,Int32 readBytes,AsyncProtocolRequest asyncRequest)(位于System.Net.Security.SslState.StartReceiveBlob(字节[]缓冲区,AsyncProtocolRequest asyncRequest))。 System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)处的System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst,Byte []缓冲区,AsyncProtocolRequest asyncRequest)处的CheckCompletionBeforeNextReceive(ProtocolToken消息,AsyncProtocolRequest asyncRequest) System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔保持SyncCtx)在.System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调) ,对象状态)在System.Net.TlsStream.ProcessAuthentication(LazyAs yncResult结果)位于System.Net.ConnectStream.WriteHeaders(布尔型异步)处,位于System.Net.ConnectStream.WriteHeaders(字节[]缓冲区,Int32偏移量,Int32大小)

1 个答案:

答案 0 :(得分:0)

只需删除这些行即可解决该问题。

ServicePointManager.ServerCertificateValidationCallback = delegate
{
    return true;
};