Thursday, 14 July 2011

Non expected exception on IPAddress.TryParse

Lately, for the one of our client we implemented a functionality which uses Geo Location as a basic visitor recognition. The problem appeared after the functionality had been promoted to the live environment - it simple did not work. After a quick investigation we founded that the problem is caused by Akamai which acts as a proxy for whole domain.

The solution itself is pretty simple. Akamai can be configured so that it sends additional Http Request Header with original IP. I just thought that some basic validation on this header value would be great, so I have added something like code below:
var headerIp = request.Headers["True-Client-IP"];
IPAddress akamaiIpAddress = IPAddress.None;
var isValidIp = IPAddress.TryParse(headerIp, out akamaiIpAddress);

As you can see I laveraged on IpAddress class to determine whether sent header is correct. The problem was that if there was no header I had had the exception on that line. Why? The answer is very simple, and very unexpected - you can not pass null as a first parameter. I changed this line slightly in the following manner:

var headerIp = request.Headers["True-Client-IP"] ?? string.Empty;

and problem disappeared. I always thought that TryParse method on any object should swallow any exception, because it is expected from it. This is one of the most deceiving thing I have met in .NET. Does anyone know if any other TryParse method potentially throws exceptions as well?