.NET - Get protocol, host, and port

后端 未结 7 943
情歌与酒
情歌与酒 2020-11-28 19:18

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

7条回答
  •  春和景丽
    2020-11-28 19:40

    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.

    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 http://www.mywebsite.com.

    If the port number had been something other than 80, it would be included in the result.

提交回复
热议问题