Consuming Webservices over HTTPS (SSL)

When Webservices are used, a common concern is security: SOAP messages are transferred in plain text over the network, so anyone with a sniffer could intercept the SOAP message and read it. In my opinion this could happen also to binary data, but probably it requires a little bit more hacker skills. So a solution is to use HTTPS (SSL) instead of HTTP, so the communication is encrypted. To accomplish this, you need to get and install a certificate (issued by a Certificate Authority) on your webserver. In a production environment you would buy a certificate from Verisign or another well known CA, or you would install your own CA, which is a component of Windows Server. If you only want to play with HTTPS, SSL and certificates or your project is in the development phase, you can also generate a test certificate using the MakeCert.exe tool (included in the .NET Framework SDK). After that you have to add this certificate to a website in IIS, and set a port which HTTPS should use.

When you browse to a HTTPS site, you probably get a dialog window asking you if you want to trust the certificate provided by the webserver. So the responsibility of accepting the certificate is handled by the user. Let's get back to the webservice scenario, if you want to invoke a webservice located on a webserver which uses SSL and HTTPS there is a problem. When you make the call from code, there is no dialog window popping up, and asking if you trust the certificate (luckily because this would be pretty ugly in server-side scenarios); probably you'll get following exception:
An unhandled exception of type 'System.Net.WebException' occurred in system.dll

Additional information: The underlying connection was closed: Could not establish trust relationship with remote server.

But there is a solution for this problem, you can solve this in your code by creating your own CertificatePolicy class (which implements the ICertificatePolicy interface). In this class you will have to write your own CheckValidationResult function that has to return true or false, like you would press yes or no in the dialog window. For development purposes I've created the following class which accepts all certificates, so you won't get the nasty WebException anymore:
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
 public TrustAllCertificatePolicy()

 public bool CheckValidationResult(ServicePoint sp,
  X509Certificate cert,WebRequest req, int problem)
  return true;

As you can see the CheckValidationResult function always returns true, so all certificates will be trusted. If you want to make this class a little bit more secure, you can add additional checks using the X509Certificate parameter for example. To use this CertificatePolicy, you'll have to tell the ServicePointManager to use it:
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
This must be done (one time during the application life cycle) before making the call to your webservice.


  • can you give mo details

  • What kind of details are you looking for??

  • Sorry, but I try your solution and it doesn´t work.

    Do you know what can be happening?

    My code is:

    public __gc class MyCertificateValidation : public ICertificatePolicy



    bool CheckValidationResult(ServicePoint* , X509Certificate* ,

    WebRequest* request, int problem)


    return true;



    System::Net::ServicePointManager::CertificatePolicy = new MyCertificateValidation();

    HttpWebRequest* wrq = static_cast<HttpWebRequest*> (WebRequest::Create(url));

    HttpWebResponse* hwr = static_cast<HttpWebResponse*>(wrq->GetResponse());

    Stream* strm = hwr->GetResponseStream();

    FileStream* fs = new FileStream(fpath,FileMode::Create,FileAccess::Write);

    BinaryWriter* br = new BinaryWriter(fs);

    int b;

    while((b=strm->ReadByte()) != -1)






  • Hi,

    Your blog contains good info. Keep it up.

  • I've been trying to use the webservices over SSL and have also been having problems. I only get a problem when I do an iisreset and don't use the webservice straight away. If I start up another site (or if another site gets used before the webservice is called) then the webservice fails with either a proxy authentication error 407 (behind proxy on the development machine) or a "Could not establish secure channel for SSL/TLS" on the external server.

    I'm using .net 1.0 sp2 with C# and I have an internal webservice calling an external webservice over SSL. The webservice works fine for the most part but it obviously a problem if it happens at all. And I've also tried creating a test certificate and getting the same error with that. Many thanks

  • Mmm, I don't know what could be the problem... I suggest you post your question in the IIS or ASP.NET newsgroup.

  • I have been getting a "Could not establish secure channel for SSL/TLS" error, as well. The interesting thing is that it only happens on an XP machine running the client app. I install and run the same web service client on my 2000 Pro machine with no problem. The web service is hosted on a 2000/IIS5 machine.

    We are using a proxy server but both machines access the same one.

    Has anyone found a solution to this? Thanks.

  • I used this with a WebClient that wasn't accepting a certificate and it worked fine. Great blog!!!

  • Do you have this code in VB somewhere? We're using VB.Net for our ASP.Net pages and I can't get a decent conversion for this

  • This post was very helpful! Thanks!

  • Larry, yes my solution is for .NET. I don't know how to accomplish this in VB6...

  • I am developing a client that consumes a webservice over https.

    The web server is set up to require client certificate.

    how should I select the client certificate and provide it to the webservice




  • You can use the ClientCertificates.Add method of the proxy class.

  • Very good! solved my problem

  • With C# this work beatifull, but i need something like this in FoxPro 8, some body can help me??

  • Well anyone out their interested in a consulting job because we could sure use some help with the webservices client we have to design.

    This is what I need. A form that consumes a .NET Webservice. Let me explain: We have a page with Wireless Service Providers, once an agent selects a Service Provider it will take them to another page that displays the PINs denomination choices. Once the agent chooses what PIN denomination the customer wants, it calls the webservice using the PG_GetPin procedure to request a single PIN by product SKU, the system will reply with a PIN on a confirmation page and our SQL Server 'CCS_Wireless' table is updated. The company has provided the guidelines for developing the project but I don't have a clue where to start.

    Can anyone help? Supposedly, it is simple but when you have no experience it doesn't look that simple. Please email me at

    Thanks for any assistance.

  • Does anyone have the solution for the C++.







    this call fails when g_bsWSDLFile is "https://.../.../x.jws?wsdl"

    its successful when g_bsWSDLFile is "http://.../.../a.jws?wsdl"

    I tried to use the ConnectorProperty of "UseSSL" but that's possible only after my initialization succeeds.

    Any help is greatly appreciated. Thanks

  • We just started getting this problem talking to a partners webservice.

    We had a problem with our own webservice with keep-alives - where load balancers would interfere with the keepalive and hose the connection.

    Could this be another form of the keepalive problem?

  • Hi all!

    I'd like to solve exactly the same problem. But whatever I try it doesn't work.

    I am trying to read a webpage using the HttpWebRequest methods. When the URL is not secured (http://) it works fine, using the HTTPS protocol I get the

    "The underlying connection was closed: Could not establish trust relationship with remote server."


    I implemented the class TrustAllCertificatePolicy like shown here. But also this did not help... Is there anyone with another idea?

  • I have a problem when trying to using:

    xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    If I try to attach a french character ie ç. The server can't seem to understand it.

    Please Help!

  • The web server is set up to require client certificate.

    How should I select the client certificate and provide it to the webservice ?

    With C# ou VB.NET this work beatifull, but i need something like this in FoxPro 6 or 8 or VB6 , some body can help me please??

  • To: Jan (the blog owner)

    Thanks a ton!!!

    Your solution saved my a**!

    For the last 2 days, I have been banging my head against the wall and my problem was "exactly" the same as the post attempts to solve. This was a perfect, natural fit for my problem.

    As soon as I implemented the ICertificatePolicy interface and used the ServicePointManager class, the certificate issue went away. None of this is easy to glean from the MSDN documentation.

    I am sure that even a couple years from now, there will be folks who will find this info. useful.

    Thanks again.

  • I could not all a web reference using Visual Studio.NET to a webservice running in SSL. Iam getting an error stating

    "The proxy settings on this computer are not configured correctly for web discovery. Click the Help button for more information."

    Can someone tell me the steps for adding webreference a Webservice running in SSL.

  • I have added the following class to my code for consuming a webservice (I added it to the form1.cs). I

    want to be able to accept all certificates for testing etc..

    public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy


    public TrustAllCertificatePolicy()


    public bool CheckValidationResult(ServicePoint sp,

    X509Certificate cert,WebRequest req, int problem)


    return true;



    However, when I try to build the application, I get the build error:

    'TrustAllCertificatePolicy' does not implement interface member


    , System.Security.Cryptography.X509Certificates.X509Certificate,

    System.Net.WebRequest, int)'

  • thanks very much for the tip, Jan

  • Hello everybody

    i have the following code to access an application via https:


    System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

    httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

    X509Certificate cer = X509Certificate.CreateFromCertFile(@"c:\CertificadoCliente.cer");


    httpWebRequest.Method = "POST";

    httpWebRequest.ContentLength = stringPost.Length;

    streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());



    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());

    respuesta = streamReader.ReadToEnd();



    Although the connection is created (i think the certificates are correctly installed), i got an exception when i try to close the streamWriter:

    "Cannot access a disposed object named \"System.Net.TlsStream\"."

    As you can see i have created the TrustAllCertificatePolicy class, but i still get that exception. Could anyone help me?

    Thanks in advance. Patricio.

  • Very helpful. Thanks so much!

  • I have found the solution by myself, the problem was that i have the client certificate installed only for the machine account. I have also installed it for the current user and now all it´s working fine.

    Thanks a lot.


  • Hi,

    When using "System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();"

    Is there a need to call to CheckValidationResult function? If yes where in the code? Because there is no call to this function from your example.

    Does it works for SSL HTTP POST?



  • Hi,

    When doing HTTP POST to SSL I a getting

    Cannot access a disposed object named "System.Net.TlsStream".

    Object name: "System.Net.TlsStream".

    Is there a way to solve this?


  • Thanks, for this information! It was very helpful!

    Here's the .NET 2.0 version:

    public static bool TrustAllCertificateCallback(object sender,
    X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
    return true;

    The following line needs to be called once before the web service is accessed (for example in main or the constructor of your main object):
    ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificateCallback;

  • It works in management envirorment, but how to handle it in umanagement envirorment with c++

  • Dear All,

    Please tell me .. what should i pass for

    sp,cert,req and problem in

    public bool CheckValidationResult(ServicePoint sp,
    X509Certificate cert,WebRequest req, int problem)



  • hi, after "System.Net.ServicePointManager.CertificatePolicy = New MyCertificateValidation" (i am using vb.net2003), do i need to call the function CheckValidationResult()?
    If yes, what are the actual parameters to pass?

    I am still the error

    [EntryPointNotFoundException: ?]
    System.Net.NativeNTSSPI.EnumerateSecurityPackagesW(Int32& pkgnum, IntPtr& arrayptr) +0
    System.Net.SSPISecureChannelType.EnumerateSecurityPackages(Int32& pkgnum, IntPtr& arrayptr)
    System.Net.SSPIWrapper.EnumerateSecurityPackages(SSPIInterface SecModule)
    System.Net.SSPIWrapper.GetSupportedSecurityPackages(SSPIInterface SecModule)

    [TypeInitializationException: The type initializer for "System.Net.SecureChannel" threw an exception.]
    System.Net.SecureChannel..ctor(String hostname, X509CertificateCollection clientCertificates) +0
    System.Net.TlsStream.Handshake(ProtocolToken message)

    [WebException: The underlying connection was closed: Could not establish secure channel for SSL/TLS.]
    System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)
    System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
    TP.CisMis.Opal.Web.ProvideLetterProxy.ProvideLetter.MyInitialize(String a, String b, String c, String d, String e) in C:\_MyDocs\Opal\OpalSoln\Web\Web References\ProvideLetterProxy\Reference.vb:83
    TP.CisMis.Opal.Web.Login.btnSignIn_Click(Object sender, EventArgs e) in C:\_MyDocs\Opal\OpalSoln\Web\Login.aspx.vb:114
    System.Web.UI.WebControls.Button.OnClick(EventArgs e)
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)

  • Thanks for a very useful post.

  • Moritz, do you have any idea of how to do the same in .NET Compact Framework 2.0?
    In CF 2.0 the property CertificatePolicy of ServicePointManager is obsolete, and the ServerCertificateValidationCallback is supported in .NET Framework 2.0 but not in .NET Compact Framework 2.0.

    Any idea of how resolve the problem?

    Thanks in advance.

  • Thank you. Both the original version of the code in the post and the .NET 2.0 version work great. I am supporting both .NET 2003 and .NET 2005 so I needed both.

  • Your post proved very useful.


  • How to call
    public bool CheckValidationResult(System.Net.ServicePoint srvPoint, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Net.WebRequest request, int certificateProblem) ?
    How and what to pass as srvPoint, certificate, request, certificateProblem?
    Please inform on this

  • dirt cheap airline tickets [url=]dirt cheap airline tickets[/url]

  • ativan [url=]ativan[/url]

  • dirt cheap airline tickets [url=]dirt cheap airline tickets[/url]

  • Hi, I've tried this and it does seem to remove the webexception about server trust as mentioned, except I now get something new, it now returns:
    System.Net.WebException: The request failed with the error message: -- Redirecting...

    Any ideas?

  • cheap flight [url=]cheap flight[/url]

  • cheap airline tickets [url=]cheap airline tickets[/url]

  • cheap airfare [url=]cheap airfare[/url]

  • dirt cheap airline tickets [url=]dirt cheap airline tickets[/url]

  • cheep tickets [url=]cheep tickets[/url]

  • flight las vegas [url=]flight las vegas[/url]

  • cheap ticket [url=]cheap ticket[/url]

  • cheep flights [url=""]cheep flights[/url]

  • cheep airfare [url=""]cheep airfare[/url]

  • cheap tickets russia [url=]cheap tickets russia[/url]

  • cheap airfare [url=]cheap airfare[/url]

  • cheap flight [url=]cheap flight[/url]

  • replica handbag
    [url=]replica handbag[/url]

  • chanel sunglasses
    [url=]chanel sunglasses[/url]

  • For the record, this is how you do it in .Net 2.0

    Private callback As New System.Net.Security.RemoteCertificateValidationCallback(AddressOf RemoteCertificateValidationCallback)

    Private Function RemoteCertificateValidationCallback(ByVal sender As Object, ByVal cert As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
    Return True
    End Function

    System.Net.ServicePointManager.ServerCertificateValidationCallback = callback

  • Thanks that helps. Just a note that in .NET 2.0 System.Net.ServicePointManager.CertificatePolicy is obsolete and instead, you are expected to define the ServicePointManager.ServerCertificateValidationCallback callback method to do the same thing. This callback has the same signature as ICertificatePolicy.CheckValidationResult, but with the use of parameter-less anonymous methods, you can simply do the following to achieve the same result:

    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

  • This post was very helpful! Thank you very much!

  • Hi,
    I am trying to download a file from ssl protected link , with WebRequest.
    I tried to use your class but the stream that i am geting is empty.
    Can you tell me please if i am doing something wrong?
    The Code :

    ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
    HttpWebRequest webRequest1 = WebRequest.Create(d) as HttpWebRequest;
    webRequest1.KeepAlive = true;
    webRequest1.CookieContainer = cookies;
    webRequest1.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    webRequest1.Headers.Set("Accept-Language", "en-us,en;q=0.5");
    webRequest1.Headers.Set("Accept-Encoding", "gzip,deflate");
    webRequest1.Headers.Set("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    webRequest1.Headers.Set("Keep-Alive", "300");
    WebResponse myResponse1 = webRequest1.GetResponse();
    Stream ReceiveStream1 = myResponse1.GetResponseStream();
    SaveStreamToFile(@"C:\file.csv", ReceiveStream1);


  • [url]]cheap flight ticket[/url] cool

  • Thanks very much ! 非常感谢!

  • Hey, Great work man...

    I just copied it and it worked !

  • works great ... thanks 4 solving that problem

  • Manish was right. A few years later and this blog post is still helping.

    Thanks Jan. It really did work.

    And besides, you can do you're own code inside of the CheckValidationResult method, instead of simply returning 'True'.

  • The posted code works great, my question is about selecting the ClientCertificate that should be put into the request. I have a windows application that uses many Web Services that use SSL. Is there a way i can make the Internet Explorer Certificate selection box popup so the user can choose the certificate they want to use? I wrote my own dialog box which shows all the certificates in the user's Personal store, and they can choose which one to use from that. The problem with my own dialog box is that, unlike IE, I don't know how to filter out which certificates are not valid based on the certificate the server is using. So my dialog box might have 4 Certificates listed in it, but only 2 will work for the server. I don't know what logic IE uses to eliminate the others. I would have thought that the server Cert and the client cert would have to have identical CA's but that does not appear to be the case. So I either need the logic that should be used, or more preferably, i'd like to show the dialog box that IE shows so that they can select their cert from there. can you help?

  • Thanks heaps, - just what I was looking for :)

  • 1000 Thanks. This was just what I was searching for

  • Thanks a lot. This was a good solution to the problems we faced.

  • This certificatePolicy overriding was such a lifesaver here at the corp. Thanks a zillion!

    Jorge Silva,
    PG Stream.

  • Happy bear wanna fear

  • Implemented this with no problems... Thanks!

    I encountered this problem when working with a 3rd party dev environment and conditionally set the certificate policy based on the #if DEBUG directive so I wouldn't have to worry about it when moving to production.

    I appreciate the tip!

    - g

  • Hi,

    I am facing a problem with SSL on my website. My solution is divided in three part. 1. One web application and 2. Two Web Services(Business and Data web services).

    Webapplication is hosted on one machine and two web services are hosted on another machine.

    I installed the certificate on the Web Application machine only.

    When I am browsing my website I am getting follwing exception in my log file but my pages are displayed properly without any problem.

    "the underlying connection was closed. could not establish trust relationship for the SLL/TLS secure channel"

    Can anyone help me?

    Virendra Jhala

  • Brunettes vs blondies, who is more clever?

  • Hi,

    I am trying to create a class (which accepts all certs) like so in VB.NET:

    Public Class CertificatePolicy
    Implements System.Net.ICertificatePolicy

    Public Sub New()
    End Sub

    Public Function CheckValidationResult(ByVal sp As System.Net.ServicePoint, ByVal cert As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal req As System.Net.WebRequest, ByVal problem As Integer) As Boolean
    Return True
    End Function
    End Class

    I am getting a compile time error:
    Class 'CertificatePolicy' must implement 'Function CheckValidationResult(srvPoint As ServicePoint, certificate As Security.Cryptography.X509Certificates.X509Certificate, request As WebRequest, certificateProblem As Integer) As Boolean' for interface 'System.Net.ICertificatePolicy'.

    If anyone has any idea please let me know,

  • Reno :

    Try changing the Class name to something like MyCertificateValidation instead of CertificatePolicy

    Hopefully that will fix it.

  • luogo interessante, soddisfare interessante, buon!

  • Luogo molto buon:) Buona fortuna!

  • Hi Sam! Photos i send on e-mail.
    Green,Hi Sam! Photos i send on e-mail.

  • Hi there, i have a problem a have to consume a webservice located on a webserver which uses SSL and HTTPS and I do not what to do, please could you help me!

  • should look like this in VB:

    Public Class MyCertificateValidation
    Implements ICertificatePolicy

    ' Default policy for certificate validation.
    Public Shared DefaultValidate As Boolean = False

    Public Function CheckValidationResult(ByVal srvPoint As ServicePoint, _
    ByVal cert As X509Certificate, ByVal request As WebRequest, ByVal problem As Integer) _
    As Boolean Implements ICertificatePolicy.CheckValidationResult

    Return True
    End Function

    End Class

    then to make the call:

    ServicePointManager.CertificatePolicy = New MyCertificateValidation

  • Very interisting thead, but I have an additional problem, I want to call a web service (over HTTPS) from a UserControl from within IE. In this case the following call fails :

    System.Net.ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;

    I get a :

    + ex {"Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."} System.Exception {System.Security.SecurityException}

    Does someone have an idea ?

  • The code doesn't look right.

    Here's how the callback stuff works in VB --

    Private Function AcceptAllCerts( _
    ByVal sender As Object, _
    ByVal cert As Security.Cryptography.X509Certificates.X509Certificate, _
    ByVal chain As Security.Cryptography.X509Certificates.X509Chain, _
    ByVal SslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
    Return True
    End Function

    Elsewhere in the code...

    System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllCerts)

  • I have developed a web service that call another web service which need a SSL connection.

    I use the wizard in Visual Studio 2006

    Therefore I pass, to be able to connect, I pass credential and certificate
    All ok.

    I see the functions of the called webservice, but the error that I get is:

    The request was aborted: Could not create SSL/TLS secure channel.

    How I can resolve the problem?

  • it worked beautifully. keep it up. good info.

  • High Five to you.

    Thanks - this saved a lot of troubleshooting time for me!

  • Thanks! Great Forum!!!

  • Thanks a lot, this forum is very helpful!

  • Exactly what we were looking for! Thanks!

  • System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

    Just add this string to your code and you wiill not need to redefine CertificatePolicy class ...

  • Hi,
    I face a problem while adding web reference to a web service hosted on a secure server ( https:// ).
    When I try to add reference from this URL i get a error which reads as follows:-

    Unable to download following files.
    Do you want to skip these files and continue?

    If I continue with it then the reference is added but the wsdl and the reference.cs which get added automatically are not available.
    Those are the ones which I need to modify and put the soap authentication code in.
    I have to put something generic because I work on local machine but my code will be put on some other machine for execution so local changes won't solve my problem.

    Can anyone help please?

  • Moritz's solution seems to be working.

    Thank you all for pitching solutions to this!

  • WOW....... This one is perfect.... I got my problem resolved.... The biggest thing is this was the first webservice of my life and I put it on SSL with the help of this :)

    Damn good man :)

  • OK, I've implemented the callback delegate which is supposed to validate the certificate (and seemingly does for many here)

    ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {return true;};

    Problem is, the callback is never invoked. And the end result is the same "The ServicePointManager does not support proxies of https scheme"

    Any ideas?

  • Great tip! I have a very controlled setup and I know the SSL site I'm downloading from is always trustable, and certificates suddenly became an issue. This nicely fixed that, thanks!

Comments have been disabled for this content.