小编典典

ssl时如何忽略证书检查

c#

我正在尝试找到一种在请求Https资源时忽略证书检查的方法,到目前为止,我在Internet上找到了一些有用的文章。

但是我仍然有一些问题。请检查我的代码。我只是不明白代码ServicePointManager.ServerCertificateValidationCallback是什么意思。

什么时候调用该委托方法?还有一个问题,我应该在哪里写这段代码?在ServicePointManager.ServerCertificateValidationCallback执行之前还是之前Stream stream = request.GetRequestStream()

public HttpWebRequest GetRequest()
{
    CookieContainer cookieContainer = new CookieContainer();

    // Create a request to the server
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_remoteUrl);

    #region Set request parameters

    request.Method = _context.Request.HttpMethod;
    request.UserAgent = _context.Request.UserAgent;
    request.KeepAlive = true;
    request.CookieContainer = cookieContainer;
    request.PreAuthenticate = true;
    request.AllowAutoRedirect = false;

    #endregion

    // For POST, write the post data extracted from the incoming request
    if (request.Method == "POST")
    {
        Stream clientStream = _context.Request.InputStream;
        request.ContentType = _context.Request.ContentType;
        request.ContentLength = clientStream.Length;

        ServicePointManager.ServerCertificateValidationCallback = delegate(
            Object obj, X509Certificate certificate, X509Chain chain, 
            SslPolicyErrors errors)
            {
                return (true);
            };

            Stream stream = request.GetRequestStream();

            ....
        }

        ....

        return request;
    }
}

阅读 681

收藏
2020-05-19

共1个答案

小编典典

由于只有一个全局ServicePointManager,因此设置ServicePointManager.ServerCertificateValidationCallback将产生以下结果:所有后续请求都将继承此策略。由于它是全局“设置”,因此最好在Global.asaxApplication_Start方法中进行设置。

设置回调将覆盖默认行为,您可以自己创建自定义验证例程。

2020-05-19