I have a relative or absolute url in a string. I first need to know whether it is absolute or relative. How do I do this? I then want to determine if the domain of the url is in an allow list.
Here is my allow list, as an example:
string[] Allowed =
{
"google.com",
"yahoo.com",
"espn.com"
}
Once I know whether its relative or absolute, its fairly simple I think:
if (Url.IsAbsolute)
{
if (!Url.Contains("://"))
Url = "http://" + Url;
return Allowed.Contains(new Uri(Url).Host);
}
else //Is Relative
{
return true;
}
For some reason a couple of good answers were deleted by their owners:
Via @Chamika Sandamal
and
The UriParser and implementations via @Marcelo Cantos
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 thebuilder.Host
property to get the actual domain. If you do decide to do more processing, don't forget about URLs with complex TLDs likebbc.co.uk
.