我一直觉得我在重新造轮子,所以我想问问这里的人群。假设我有这样一段代码片段:
string protocol = "http"; // Pretend this value is retrieved from a config file
string host = "www.google.com"; // Pretend this value is retrieved from a config file
string path = "plans/worlddomination.html"; // Pretend this value is retrieved from a config file
我想要构建网址 "http://www.google.com/plans/worlddomination.html"。我通常会写类似以下的冗长代码:
protocol = protocol.EndsWith("://") ? protocol : protocol + "://";
path = path.StartsWith("/") ? path : "/" + path;
string fullUrl = string.Format("{0}{1}{2}", protocol, host, path);
我真正想要的是类似以下API:
UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();
我相信这个在.NET框架中一定有实现,但是我还没有找到。
如何构建防错(即永远不会形成格式错误的)URL的最佳方法?