设定证书连接

1.设置config文件

 <binding name="basichttp1" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                    bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="TransportWithMessageCredential">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>

 <endpoint address="https://www.xxx.x/xxxxx.svc"
                binding="basicHttpBinding" bindingConfiguration="basichttp1" behaviorConfiguration="myClientBehavior"
                contract="AFCSSLServices.ITransportService" name="basichttp">
    <identity>
     <certificate encodedValue="MIIC3jCCAcagAwIBAgIQQuEJ+Wt0+pdISf2c4iyzvzANBgkqhkiG9w0BAQUFADAYMRYwFAYDVQQDEw1ETVpUUkFQRVpFQUZDMB4XDTEzMDgxNTEzNTMyOVoXDTE0MDgxNTAwMDAwMFowGDEWMBQGA1UEAxMNRE1aVFJBUEVaRUFGQzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOb1LfBTffU0oWamgWMelrUEMmfIDO2sSkcGYO90cZ8HENjbZtJ40GToeYphK0mgkurlWW+NbjKec/o+FER26+hmkq5hIh4PitgKm1+4Q5osY4Xe5qyVt4u2mlubTwAxLVPGViKLQ3aPUe2rSschOtnj2/jbg4i/mieY6HRAxbiySGrmXzMrXWyGTSYqYZgLL44T2MkURLCAhk+pX8zDajReKPXAphYl+KUrLpI1rJktw8B2YDQJ4vlIiItSWP95yBPSJHofL2swWM5L9aRU7xPrFzx5ruluuzNPPSV9jbNa7gqPJQKq3tvYYo0C7TLyYVr4KidqBUX3yG/nh9BV850CAwEAAaMkMCIwCwYDVR0PBAQDAgQwMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4IBAQCPDFASPyrbk47KdFlRtfhyhR/yrooA0lIAew4hiKEfxyrIYINZjSOxi+Nd365tMMviqA9HWWAASdLxUk/4y5lpmG1BB39WOKiCFoy5rZa/AYNeBeKI/6WovanYM5dD/oU1Y5gCnY+NHJyOio6Z4klOAEWaSBx/Sas+YI0iqjDvzlSL6+z5+aZsRVyVZi4/KlLkWUGkohpGanNcq7phWMfNsb+5ZDE87dVYDzjV67yJ3UwuFPkg7zGeHVXOvEYUONuOzODEIg77V7Fr2xo1fCTXcj3CSdfJgMt+q0itVX0J1wILp//xLd3xR1GYEwffe2BR1MZ1/p0aJn2lAsySDc5K" />
    </identity>
   </endpoint>

<behaviors>
        <endpointBehaviors>
          <behavior name="myClientBehavior">
            <clientCredentials>
              <serviceCertificate>
                <!--<authentication certificateValidationMode="None" />-->
                <authentication  certificateValidationMode="Custom"  customCertificateValidatorType="WcfTestApp.MyX509Validator,WcfTestApp" />
              </serviceCertificate>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>

2.增加一个 类MyX509Validator

class MyX509Validator : X509CertificateValidator     {         /// <summary>         /// Validates a certificate.         /// </summary>         /// <param name="certificate">The certificate the validate.</param>         public override void Validate(X509Certificate2 certificate)         {             //// validate argument             if (certificate == null)                 throw new ArgumentNullException("X509认证证书为空!");

            //check if the name of the certifcate matches             //if (certificate.SubjectName.Name != System.Configuration.ConfigurationManager.AppSettings["CertName"])             //    throw new SecurityTokenValidationException("Certificated was not issued by thrusted issuer");

        }     }

3.增加一个类CertificatePolicy

 public static class Util
    {
        public static void SetCertificatePolicy()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertifateValidate;
        }
        public static bool RemoteCertifateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            System.Console.WriteLine("warning , trust any certificate");
            return true;
        }
    }

4.

 WcfTestApp.AFCSSLServices.TransportServiceClient tsvssl = new WcfTestApp.AFCSSLServices.TransportServiceClient();
                tsvssl.ClientCredentials.UserName.UserName = "user";
                tsvssl.ClientCredentials.UserName.Password = "xxx";
                Util.SetCertificatePolicy();
                tsvssl.Open();

原文地址:https://www.cnblogs.com/BinZeng/p/3273157.html