C#实现https双向认证的实例代码

发布时间:2020-07-13编辑:脚本学堂
分享一例c#实现的https 双向认证的代码,例子很简单,主要学习下https 双向认证在c#代码中的实现方法,有需要的朋友参考下吧。

本节内容:
C#实现https双向认证

操作方法,如下:
1,把浏览器中的证书导出为cer文件。
2,https 双向认证

例子:
 

复制代码 代码示例:
using System; 
using System.Net; 
using System.IO; 
using System.Security.Cryptography.X509Certificates; 
using System.Text; 
using System.Net.Security; 
 
public partial class About : System.Web.UI.Page 

    protected void Page_Load(object sender, EventArgs e) 
    { 
       // string url = "https://192.168.6.120/"; 
        ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback; 
        //Uri uri = new Uri("https://www.jb200.com/"); 
   
        Uri uri = new Uri("https://192.168.6.120/"); 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
        X509Certificate cer = new X509Certificate("F:csharp2.cer"); 
        request.ClientCertificates.Add(cer); 
 
        HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
        string encoding = response.ContentEncoding; 
        if (encoding == null || encoding.Length < 1) 
        { 
            encoding = "UTF-8"; //默认编码 
        } 
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); 
        Response.Write(reader.ReadToEnd()); 
        //Console.Write(reader.ReadToEnd()); 
        response.Close();  
    } 
    public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
    { 
        if (sslPolicyErrors == SslPolicyErrors.None) 
            return true; 
        return false; 
    }