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

48

我一直觉得我在重新造轮子,所以我想问问这里的人群。假设我有这样一段代码片段:

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的最佳方法?


阅读Alex Black的答案,然后点击此处:http://social.msdn.microsoft.com/Search/en-US/?Refinement=27%2c117&Query=Uri+Builder - John Saunders
2个回答

51

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!"
    });

有一个新的伴侣库,扩展了流畅链与HTTP客户端调用,并包括一些巧妙的测试功能。完整的包在NuGet上可用: < p >< code > PM> Install-Package Flurl.Http

或者只是独立的URL构建器: < p >< code > PM> Install-Package Flurl


51

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接