Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用部件在C#中可靠地构建URL?_C#_Url - Fatal编程技术网

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

如何使用部件在C#中可靠地构建URL?,c#,url,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

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

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
protocol = protocol.EndsWith("://") ? protocol : protocol + "://";
path = path.StartsWith("/") ? path : "/" + path;    
string fullUrl = string.Format("{0}{1}{2}", protocol, host, path);
我想建立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
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的最佳方法是什么?

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

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!"
    });
有一个新的配套图书馆,包括一些漂亮的。NuGet上提供了完整的软件包:

PM>安装软件包Flurl.Http

或者仅使用独立的URL生成器:


PM>安装软件包Flurl

阅读Alex Black的答案,然后单击此处: