0

I'm attempting to call an api using .NET Framework 3.5

I'm trying it with HttpWebRequest but I've not had different results with WebClient

The following code works in .NET Framework 4.8, however in .NET Framework 3.5 there is a WebException thrown from GetResponse()

Code:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://abolutepathtoendpoint.aspx");
req.ContentType = "text/plain";
req.Method = "GET";
req.ContentLength = 0;

string respBody;
try
{
    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
    using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
    {
        respBody = reader.ReadToEnd();
    }

}
catch (Exception e)
{
    respBody = e.ToString();
}

Exception:

The remote server returned an error: (403) Forbidden.

I have also been able to get it to work by pasting the url into a brower, Postman and RestClient on .NET 7

1 Answers1

0

I spent 2 days looking for this, so wanted to link the question I was asking, to the answer I was looking for:

The issue is that the link is https and is secured by TLS 1.2, something not available by default in .NET 3.5

This is answered here

Just in case the links die the solution is as follows:

Add imports:

VB

Imports System.Security.Authentication
Imports System.Net

C#

using System.Security.Authentication;
using System.Net;

Add before creating HttpWebRequest

VB

Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12

C#

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

For multiple protocols

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | 
                                       (SecurityProtocolType)768 | 
                                       (SecurityProtocolType)192;
  • 192: Specifies the TLS 1.0 security protocol
  • 768: Specifies the TLS 1.1 security protocol
  • 3072: Specifies the TLS 1.2 security protocol
Community
  • 1
  • 1