Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

url

https

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.

like image 839
wickjon Avatar asked Dec 19 '13 10:12

wickjon


People also ask

How do you tell if a website is HTTP or HTTPS?

How do you tell if a site is an HTTP:// site or an HTTPS:// site? If you type in something that looks like a URL with the scheme missing, then browsers will assume you intended to put http:// in front of it. Most browsers will hide the http:// part from the address bar for non-SSL sites.

How to check if a URL is valid or not?

Given a URL as a character string str of size N .The task is to check if the given URL is valid or not. The above URL is a valid URL. Note that there is a space after https://, hence the URL is invalid. An approach using java.net.url class to validate a URL is discussed in the previous post.

Why can't I PUT HTTP://in front of a URL?

If you type in something that looks like a URL with the scheme missing, then browsers will assume you intended to put http:// in front of it. Most browsers will hide the http:// part from the address bar for non-SSL sites.

Why do some websites redirect to https instead of HTTP?

You could configure a server to redirect the URLs for some pages to HTTPS and some to HTTP. This was typically done to save on CPU power for pages where security wasn't needed. Today, CPU power is much cheaper, so it is normally better to use SSL by default.


1 Answers

try something like this:

public static bool IsHttps()
{
    return HttpContext.Current.Request.IsSecureConnection;
}

Or if you working with asp.net-web-api you can check if Request.RequestUri.Scheme is Uri.UriSchemeHttps.

like image 138
Felipe Oriani Avatar answered Oct 03 '22 01:10

Felipe Oriani