how to check if a given URL is HTTP or HTTPS in C#

Viewed 29495

I need to check if a given URL (which is not necessarily prefixed with http or https) is HTTP or HTTPs.
Is this possible in C#?
If the user gives just www.dotnetperls.com without any prefix, I must be able to identify that it is an HTTP one. Tried the following,

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.dotnetpearls.com");         
 string u = request.RequestUri.Scheme;

But this gives an Invalid URL error. It expects the protocol to be specified.

6 Answers
if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
}

I've been looking for a solution for the same as well and unfortunately I couldn't find any.

And also some websites doesn't support www as well.

So I'm sending 4 requests to find out if the website supports https and finding the one that supports.

I know this is not a good solution but it works at least. If the first one works, I'm not calling the rest of them...

  1. WebRequest.Create("https://dotnetpearls.com");
  2. WebRequest.Create("https://www.dotnetpearls.com");
  3. WebRequest.Create("http://dotnetpearls.com");
  4. WebRequest.Create("http://www.dotnetpearls.com");

For ASP.net core the property Request.Scheme is available that works for me:

var uri = String.Format("{0}://{1}",Request.Scheme,Request.Host.Value);
Related