WebRequest Strange NotFound Error

I have two different ASP.NET Core website: admin and public. Both are running on the staging server and on the local machine.

I send a GET request to different pages to determine the runtime of different pages and ran into a problem with the admin site: all URLs of the local instance and stage always return a 404 error:

An unhandled exception of type "System.Net.WebException" occurred in System.dll

Additional Information: The remote server returned an error: (404) Not Found.

Meanwhile, the same requests in the browser usually return html pages. Requests through the HttpWebRequest to the public site always also return 200 Status Code (OK). The code for the request I took here .

I tried adding all the headers and cookies from the browser request, but that did not help. I also tried to debug the local instance and found that no exceptions were made during the execution of the request.

Any ideas?

+5
source share
2 answers

WebException is a general way to tell you that something went wrong with the connection without telling you what it is.

To get the cause of the problem, you need to read the answer inside the catch block - the server will provide you with more detailed information.

Use Try Catch Block if you are not using alreday.

+4
source

404 - the path to the birth. The code provided in the answer in your link ( fooobar.com/questions/112569 / ... ) does not handle errors - this is a vivid example of how you may encounter problems when blindly copying code from stackoverflow :)

The modified error-handling code should look like this:

 string urlAddress = "http://google.com/rrr"; var request = (HttpWebRequest)WebRequest.Create(urlAddress); string data = null; string errorData = null; try { using (var response = (HttpWebResponse)request.GetResponse()) { data = ReadResponse(response); } } catch (WebException exception) { using (var response = (HttpWebResponse)exception.Response) { errorData = ReadResponse(response); } } static string ReadResponse(HttpWebResponse response) { if (response.CharacterSet == null) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet))) { return reader.ReadToEnd(); } } 

So, when there is an exception, you will get not only the status code, but the whole response from the server in the errorData variable.

One thing to check is a proxy browser can use HTTP proxies until your client server uses one.

+3
source

All Articles