Add a scheme to the URL if necessary

To create a Uri from a string, you can do this:

Uri u = new Uri("example.com"); 

But the problem is that the line (for example, above) does not contain the protocol, you will get an exception: " Invalid URI: The format of the URI could not be determined. "

To avoid an exception, you must make sure that the string contains the protocol, for example:

 Uri u = new Uri("http://example.com"); 

But if you take url as input, how can you add a protocol if it is missing? I mean, besides some IndexOf / Substring manipulations?

Something elegant and fast?

+53
c # uri
Mar 13 2018-11-11T00:
source share
3 answers

You can also use UriBuilder :

 public static Uri GetUri(this string s) { return new UriBuilder(s).Uri; } 

Notes from MSDN:

This constructor initializes a new instance of the UriBuilder class with the Fragment, Host, Path, Port, Query, Scheme, and Uri parameters specified in the uri.

If uri does not specify a schema, the default schema is "http:".

+111
Mar 13 2018-11-11T00:
source share

If you just want to add a scheme without checking the url, the fastest / easiest way is to use a string search, for example:

 string url = "mydomain.com"; if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) url = "http://" + url; 

A better approach would be to use Uri to also validate the URL using the TryCreate method:

 string url = "mydomain.com"; Uri uri; if ((Uri.TryCreate(url, UriKind.Absolute, out uri) || Uri.TryCreate("http://" + url, UriKind.Absolute, out uri)) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)) { // Use validated URI here } 

As @JanDavidNarkiewicz noted in the comments, Scheme checking is necessary to protect against invalid circuits when a port is specified without a circuit, for example. mydomain.com:80 .

+6
Nov 28 '14 at 10:16
source share

My solution was that there are fewer URLs for the protocols to make sure they have a protocol regular expression:

 Regex.Replace(s, @"^\/\/", "http://"); 
+2
07 Feb '13 at 8:44
source share



All Articles