WebRequest exception in .NET

I use this piece of code that checks to see if the file specified in the url exists and try it every few seconds for each user. Sometimes (most often when using a large number of users using the site) the code does not work.

[WebMethod()] public static string GetStatus(string URL) { bool completed = false; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { try { if (response.StatusCode == HttpStatusCode.OK) { completed = true; } } catch (Exception) { //Just don't do anything. Retry after few seconds } } return completed.ToString(); } 

When I look at the Windows logs, there are a few errors:

 Unable to read data from the transport connection. An existing connection was forcibly closed The Operation has timed out The remote host closed the connection. The error code is 0x800703E3 

When I restart IIS, everything works fine until the next time it happens.

+4
source share
1 answer

You put try / catch inside the using statement, while the request.GetResponse method, which can be thrown:

 bool completed = false; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { completed = true; } } } catch (Exception) { //Just don't do anything. Retry after few seconds } return completed.ToString(); 
+4
source

Source: https://habr.com/ru/post/1302593/


All Articles