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:
I need to return:
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.
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Even though @Rick has the accepted answer for this question, there’s actually a shorter way to do this, using the poorly named
Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string output = url.GetLeftPart(UriPartial.Authority);
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 of
GetLeftPart()in my example above will be
If the port number had been something other than 80, it would be included in the result.
The following (C#) code should do the trick
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Well if you are doing this in Asp.Net or have access to HttpContext.Current.Request
I’d say these are easier and more general ways of getting them:
var scheme = Request.Url.Scheme; // will get http, https, etc. var host = Request.Url.Host; // will get www.mywebsite.com var port = Request.Url.Port; // will get the port var path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx
I hope this helps. 🙂
A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.
var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);
Uri url = Request.Url; string protocol = url.Scheme;
Hope this helps.
Even shorter way, may require newer ASP.Net:
string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)
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:
Uri uri = Context.Request.Url; var scheme = uri.Scheme // returns http, https var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https:// var host = uri.Host; // return www.mywebsite.com var port = uri.Port; // returns port number
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 the
Port Number, so this is what I did:
var Uri uri = Context.Request.Url; var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Which successfully grabbed: