2015-12-17 15 views
1

当我使用Uri类来解析url时, client-lb.dropbox.com:443,Uri类无法解析该值并获得正确的结果,如url.Port:443,url.Host = client-lb.dropbox.com。在没有协议的情况下解析c#中的网址,而不是端口号

var urlValue = "client-lb.dropbox.com:443"; 
var url = new Uri(urlValue); 
Console.WriteLine("Host : {0}, Port {1} ", url.Host, url.Port); 

结果:

Host : , Port -1 

我怎样才能解决这个使用Uri类?任何建议都理解..

+1

http://stackoverflow.com/questions/5289739/add-scheme-to-url-if-needed –

+0

它不工作:( –

回答

3
var urlValue = "http://client-lb.dropbox.com:443"; 
var url = new Uri(urlValue); 
Console.WriteLine("Host : {0}, Port {1} ", url.Host, url.Port); 

响应:

Host : client-lb.dropbox.com, Port 443 
+0

它是443端口,因此应该是HTTPS – niksofteng

+0

@nvartak:是的,它很可能是,但443只是一个端口,他可以使用任何端口,如果他想,所以我就这样离开它:(=) –

+0

是的,我知道如果我添加一个协议,它可以解析,但重点是所以为了使用Uri类,我需要添加方案? –

0

地址应该像[协议]://主机名:[端口],由默认HTTPS端口443和用于http端口是80.

协议有关于它们的默认端口的信息。但端口无法将它们与协议相关联。

0

我已经重新编写了这个解析器,并感谢Trotinet项目的基本实现。

private static void ParseUrl(string url) 
     { 
      string host = null; 
      var port = 123; 
      var prefix = 0; 
      if (url.Contains("://")) 
      { 
       if (url.StartsWith("http://")) 
        prefix = 7; // length of "http://" 
       else if (url.StartsWith("https://")) 
       { 
        prefix = 8; // length of "https://" 
        port = 443; 
       } 
       else 
       { 
        throw new Exception("Expected scheme missing or unsupported"); 
       } 
      } 

      var slash = url.IndexOf('/', prefix); 
      string authority = null; 
      if (slash == -1) 
      { 
       // case 1 
       authority = url.Substring(prefix); 
      } 
      else 
       if (slash > 0) 
        // case 2 
        authority = url.Substring(prefix, slash - prefix); 

      if (authority != null) 
      { 
       Console.WriteLine("Auth is " + authority); 
       // authority is either: 
       // a) hostname 
       // b) hostname: 
       // c) hostname:port 

       var c = authority.IndexOf(':'); 
       if (c < 0) 
        // case a) 
        host = authority; 
       else 
        if (c == authority.Length - 1) 
         // case b) 
         host = authority.TrimEnd('/'); 
        else 
        { 
         // case c) 
         host = authority.Substring(0, c); 
         port = int.Parse(authority.Substring(c + 1)); 
        } 
      } 
      Console.WriteLine("The Host {0} and Port : {1}", host, port); 
     } 
相关问题