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

Mik*_*ike 36 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
Run Code Online (Sandbox Code Playgroud)

我想构建网址" 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);
Run Code Online (Sandbox Code Playgroud)

我真正想要的是某种API,如:

UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();
Run Code Online (Sandbox Code Playgroud)

我不得不相信它存在于某个.NET框架中,但我无处可见.

什么是构建万无一失(即从未畸形)网址的最佳方式?

Tod*_*ier 29

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!"
    });
Run Code Online (Sandbox Code Playgroud)

有一个新的伴随库,它通过HTTP客户端调用扩展了流畅的链,并包含一些漂亮的测试功能.NuGet提供完整的软件包:

PM> Install-Package Flurl.Http

或者只是独立的URL构建器:

PM> Install-Package Flurl