Question

I have an application which sometimes must do some requests to the server to see that those requests are properly blocked. In other words, the expected server answer 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 WebException is thrown on the last line.

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

Is there a way to check for server response, expecting a 403, without having to catch an exception (but avoiding using sockets directly)?

Was it helpful?

Solution

Unfortunately, this is a vexing exception in the framework, and there's no way to avoid it (while still using the HttpWebRequest class). But, as High pointed out, this exception handling will take nanoseconds, while the web request itself will take milliseconds (at best), so don't worry about it.

The WebException object has a Response property that contains the response; when you handle the exception, it's important to dispose that WebResponse object (to avoid leaking connections).

OTHER TIPS

What's taking time in the profiling is probably not the exception catching part but the actual response from the web site.

The WebException.Status property will give you the status code for the HTTP response and you can do further processing based on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top