簡體   English   中英

解析c#中沒有協議的URL而不是端口號

[英]parsing an url in c# without protocol instead with port number

當我使用Uri類來解析像client-lb.dropbox.com:443之類的URL時,Uri類無法解析該值並獲得正確的結果,例如url.Port:443,url.Host = client-lb。 dropbox.com。

 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類解決這個問題? 任何建議都表示贊賞..

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 

Url應該看起來像[protocol]:// hostname:[port],默認情況下, https端口是443, http端口是80。

協議包含有關其默認端口的信息。 但是端口無法將它們與協議相關聯。

我重寫了這個解析器,感謝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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM