How to avoid WebException for forbidden 403 response?

I have an application that sometimes needs to execute some server requests to make sure that these requests are properly blocked. In other words, the expected server response is 403 Forbidden.

With a piece of code like this:

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(protectedPage);
httpRequest.Method = WebRequestMethods.Http.Head;
WebResponse response = HttpRequest.GetResponse();

a is WebExceptionthrown into the last line.

When profiling code, this exception in the try / catch block has a performance impact that I want to avoid.

Is there a way to check the server response, expecting 403, not being able to catch the exception (but avoiding using sockets directly)?

+3
source share
2 answers

Unfortunately, this is an annoying exception within the framework, and there is no way to avoid this (when using the class HttpWebRequest), but, as High noted, exception handling will take nanoseconds, and the web request itself will take milliseconds (at best), so don't worry about that.

An object WebExceptionhas a property Responsethat contains an answer; when you handle an exception, it is important to delete this object WebResponse(to avoid connection leakage).

+3
source

What takes time in profiling is probably no exception, not the actual answer on the website.

The WebException.Status property will provide you with a status code for the HTTP response, and you can do further processing based on this.

+2

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


All Articles