Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Absolute or Relative URL

Tags:

c#

url

parsing

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; } 
like image 873
Mark Avatar asked Oct 23 '10 05:10

Mark


People also ask

Should I use absolute or relative URLs?

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.

What is difference between absolute URL and relative URL?

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.


2 Answers

bool IsAbsoluteUrl(string url) {     Uri result;     return Uri.TryCreate(url, UriKind.Absolute, out result); } 
like image 85
Muhammad Hasan Khan Avatar answered Sep 27 '22 18:09

Muhammad Hasan Khan


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

like image 22
Chris Marisic Avatar answered Sep 27 '22 18:09

Chris Marisic