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; }
An absolute URL contains more information than a relative URL does. Relative URLs are more convenient because they are shorter and often more portable. However, you can use them only to reference links on the same server as the page that contains them.
An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.
bool IsAbsoluteUrl(string url) { Uri result; return Uri.TryCreate(url, UriKind.Absolute, out result); }
For some reason a couple of good answers were deleted by their owners:
Via @Chamika Sandamal
Uri.IsWellFormedUriString(url, UriKind.Absolute)
and
Uri.IsWellFormedUriString(url, UriKind.Relative)
The UriParser and implementations via @Marcelo Cantos
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With