.NET - Get protocol, host, and port

后端 未结 7 844
情歌与酒
情歌与酒 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:23

    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);
    
    0 讨论(0)
  • 2020-11-28 19:24

    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;
    
    0 讨论(0)
  • 2020-11-28 19:25

    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:

    Uri url = Request.Url;
    string protocol = url.Scheme;
    

    Hope this helps.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-28 19:34

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题