.NET - Get protocol, host, and port

后端 未结 7 965
情歌与酒
情歌与酒 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条回答
  •  萌比男神i
    2020-11-28 19:33

    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: http://localhost:12345

提交回复
热议问题