Determine if an Absolute or Relative URL

I have a relative or absolute url in a string. First I must know if it is absolute or relative. How should I do it? Then I want to determine if the domain URL is in the permissions list.

Here is my list of permissions, for example:

string[] Allowed = { "google.com", "yahoo.com", "espn.com" } 

As soon as I know if its relative or absolute, its pretty simple, I think:

 if (Url.IsAbsolute) { if (!Url.Contains("://")) Url = "http://" + Url; return Allowed.Contains(new Uri(Url).Host); } else //Is Relative { return true; } 
+45
c # url parsing
Oct 23 2018-10-10 at
source share
3 answers
 bool IsAbsoluteUrl(string url) { Uri result; return Uri.TryCreate(url, UriKind.Absolute, out result); } 
+80
Oct 23 '10 at 5:58
source share
β€” -

For some reason, several good answers were removed by their owners:

Via @Chamika Sandamal

 Uri.IsWellFormedUriString(url, UriKind.Absolute) 

and

 Uri.IsWellFormedUriString(url, UriKind.Relative) 

UriParser and implementations via @Marcelo Cantos

+12
Apr 08 '16 at 20:27
source share

You can achieve what you want more directly with UriBuilder , which can handle both relative and absolute URIs (see example below).

@icktoofay also draws a good conclusion: be sure to specify subdomains (for example, www.google.com ) in the allowed list or do more processing in the builder.Host property to get the actual domain. If you 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) ); } } } 
+3
Oct 23 2018-10-10T00:
source share



All Articles