Jeremy Jeremy - 2 months ago 34
ASP.NET (C#) Question

.NET - Get protocol, host, and port

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?

Answer

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;
Comments