首页 > 编程 > .NET > 正文

ASP.NET1.1和2.0下进行https请求的不同实现

2024-07-10 13:09:19
字体:
来源:转载
供稿:网友


今天做项目中进行https请求时遇到这样的调试错误,内部错误:未能为 ssl/tls 安全通道建立信任关系。错误页面:根据验证过程,远程证书无效。经过分析,在浏览器中打开要进行一个安全确认。就是这个对话框引起的问题。在网上搜了一下一般的解决办法,但是搜的内容比较少,现在在这里总结一下。

using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.net;
using system.io;
using system.text;
using system.net.security;
using system.security.authentication;
using system.security.cryptography.x509certificates;

public partial class _default : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {
        //for 1.1 在2.0下servicepointmanager.certificatepolicy已经过时
        //servicepointmanager.certificatepolicy = new acceptallcertificatepolicy();
        //for 2.0
        //servicepointmanager.servercertificatevalidationcallback = new system.net.security.remotecertificatevalidationcallback(checkvalidationresult);
        httpwebrequest request = (httpwebrequest)webrequest.create("https://someurl");
        request.method = "get";
        httpwebresponse response = (httpwebresponse)request.getresponse();
        stream receivestream = response.getresponsestream();
        streamreader readstream = new streamreader(receivestream, encoding.utf8);
        page.response.write(readstream.readtoend());
        response.close();
        readstream.close();
    }
    //for 2.0
    public bool checkvalidationresult(object sender, x509certificate certificate, x509chain chain, sslpolicyerrors errors)
    {   //   always   accept  
        return true;
    }
    //for 1.1
    internal class acceptallcertificatepolicy : icertificatepolicy
    {
        public acceptallcertificatepolicy()
        {
        }

        public bool checkvalidationresult(servicepoint spoint, system.security.cryptography.x509certificates.x509certificate cert, webrequest wrequest, int certprob)
        {
            //   always   accept  
            return true;
        }
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表