【发布时间】:2010-11-11 05:13:08
【问题描述】:
我一直觉得我在重新发明轮子,所以我想我应该问问这里的人群。想象一下,我有一个这样的代码 sn-p:
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 框架中的某个地方,但我没有遇到过。
构建万无一失(即从不畸形)网址的最佳方法是什么?
【问题讨论】:
-
阅读 Alex Black 的回答,然后点击这里:social.msdn.microsoft.com/Search/en-US/…