Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:
http://www.mywebsite.com:80/pages/page1.aspx
I need to return:
http://www.mywebsite.com:80
I know I can use Request.Url.AbsoluteUri
to get the complete URL, and I know I can use Request.Url.Authority
to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.
Any suggestions?
Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named
Uri.GetLeftPart()
method.There is one catch to
GetLeftPart()
, however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output ofGetLeftPart()
in my example above will behttp://www.mywebsite.com
.If the port number had been something other than 80, it would be included in the result.
Even shorter way, may require newer ASP.Net:
The UriComponents enum lets you specify which component(s) of the URI you want to include.
Very similar to Holger's answer. If you need to grab the URL can do something like:
The Uri class provides a whole range of methods, many which I have not listed.
In my instance, I needed to grab
LocalHost
along with thePort Number
, so this is what I did:Which successfully grabbed:
http://localhost:12345
Request.Url will return you the Uri of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the Scheme property.
Sample:
Hope this helps.
The following (C#) code should do the trick
A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.