如何使用部件在C#中可靠地构建URL?

时间:2009-07-16 00:48:27

标签: c# url

我一直觉得我正在重新发明轮子,所以我想我会问这里的人群。想象一下,我有一个这样的代码片段:

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框架中,但我无处可见。

建立万无一失(即从未出错过)网址的最佳方法是什么?

2 个答案:

答案 0 :(得分:42)

答案 1 :(得分:26)

UriBuilder非常适合处理URL前面的位(如协议),但在查询字符串端没有提供任何内容。 Flurl [披露:我是作者]试图用一些流利的善良填补这个空白:

using Flurl;

var url = "http://www.some-api.com"
    .AppendPathSegment("endpoint")
    .SetQueryParams(new {
        api_key = ConfigurationManager.AppSettings["SomeApiKey"],
        max_results = 20,
        q = "Don't worry, I'll get encoded!"
    });

有一个新的伴随库extends the fluent chain with HTTP client calls并包含一些漂亮的testing features。完整的软件包可以在NuGet上找到:

PM> Install-Package Flurl.Http

或只是独立的网址构建器:

PM> Install-Package Flurl