You can achieve what you want more directly with UriBuilder
which can handle both relative and absolute URIs (see example below).
@icktoofay makes a good point as well: be sure to either include subdomains (like www.google.com
) in your allowed list or do more processing on the builder.Host
property to get the actual domain. If you do decide to do more processing, don't forget about URLs with complex TLDs like bbc.co.uk
.
using System;
using System.Linq;
using System.Diagnostics;
namespace UriTest
{
class Program
{
static bool IsAllowed(string uri, string[] allowedHosts)
{
UriBuilder builder = new UriBuilder(uri);
return allowedHosts.Contains(builder.Host, StringComparer.OrdinalIgnoreCase);
}
static void Main(string[] args)
{
string[] allowedHosts =
{
"google.com",
"yahoo.com",
"espn.com"
};
// All true
Debug.Assert(
IsAllowed("google.com", allowedHosts) &&
IsAllowed("google.com/bar", allowedHosts) &&
IsAllowed("http://google.com/", allowedHosts) &&
IsAllowed("http://google.com/foo/bar", allowedHosts) &&
IsAllowed("http://google.com/foo/page.html?bar=baz", allowedHosts)
);
// All false
Debug.Assert(
!IsAllowed("foo.com", allowedHosts) &&
!IsAllowed("foo.com/bar", allowedHosts) &&
!IsAllowed("http://foo.com/", allowedHosts) &&
!IsAllowed("http://foo.com/foo/bar", allowedHosts) &&
!IsAllowed("http://foo.com/foo/page.html?bar=baz", allowedHosts)
);
}
}
}