3

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)?

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
  • I don't see how catching that exception would affect performance at all. I mean it takes nothing compared to how long it takes to receive a webpage. – Will Dec 05 '10 at 04:38

2 Answers2

3

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).

Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108
  • @Tergiver, I think this is a situation where one use case's vexing exception is another use case's exogenous exception. `File.Open` throws if you don't have permission to read the file, `HttpWebRequest` is doing the analogous thing here. – Jeffrey Hantin Aug 28 '14 at 21:55
2

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.

Can Gencer
  • 8,822
  • 5
  • 33
  • 52