在没有协议的情况下用端口号解析c#中的url
本文关键字:口号 url 中的 协议 情况下 | 更新日期: 2023-09-27 18:27:05
当我使用Uri类解析url时,例如client-lb.dropbox.com:443,Uri类无法解析值并获得正确的结果,例如url。端口:443,url。主机=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]://主机名:[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);
}