Search code examples
c#httpwebrequest

HttpWebResponse req.GetResponse() failes


i have the following problem. when I call the getResponse () method, I get the following error message: The underlying connection was closed: Unexpected error when sending. (.Net Framework 4.0)

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.pegelonline.wsv.de/webservices/rest-api/v2/stations/Bonn.json");
            req.Method = WebRequestMethods.Http.Get;
            req.Accept = "application/json";
            req.ContentType = "application/json; charset=utf-8";

            string result = null;
            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();}

Solution

  • Upgrade your framework to a supported version. The earliest supported .NET version is 4.5.2, although you should prefer 4.6 at least.

    If you check that URL, you'll see that the target site uses TLS1.2, as it should. TLS1.2 support was added in .NET 4.5. It became a default in 4.6. .NET 4.0 just doesn't support TLS1.2

    In the .NET versions that don't use TLS1.2 as a default, you can request it by setting the ServicePointManager.SecurityProtocol setting :

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    In .NET 4.0 You could use a hack and install the .NET 4.5.2 runtime. The Tls12 value doesn't exist, but you can still set numeric value :

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
    

    I advise against this though. There aren't any serious compatibility issues between 4.0 and 4.5.2. By running a 4.0 application on a 4.5.2 runtime you'd get all of them but none of the benefits.