如何使用这些部件在 C# 中可靠地构建 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1134898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reliably build a URL in C# using the parts?
提问by Mike
I keep feeling like I'm reinventing the wheel, so I thought I'd ask the crowd here. Imagine I have a code snippet like this:
我一直觉得我在重新发明轮子,所以我想我会问这里的人群。想象一下,我有一个这样的代码片段:
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
I want to build the url "http://www.google.com/plans/worlddomination.html". I keep doing this by writing cheesy code like this:
我想建立网址“ 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);
What I really want is some sort of API like:
我真正想要的是某种 API,例如:
UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();
I gotta believe this exists in the .NET framework somewhere, but nowhere I've come across.
我必须相信这存在于 .NET 框架中的某个地方,但我没有遇到过。
What's the best way to build foolproof (i.e. never malformed) urls?
构建万无一失(即永远不会格式错误)网址的最佳方法是什么?
采纳答案by Alex Black
Check out the UriBuilder class
回答by Todd Menier
UriBuilder
is great for dealing with the bits at the front of the URL (like protocol), but offers nothing on the querystring side. Flurl[disclosure: I'm the author] attempts to fill that gap with some fluent goodness:
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!"
});
There's a new companion library that extends the fluent chain with HTTP client callsand includes some nifty testing features. The full package is available on NuGet:
有一个新的配套库,它通过 HTTP 客户端调用扩展了 fluent 链,并包括一些漂亮的测试功能。NuGet 上提供了完整的包:
PM> Install-Package Flurl.Http
PM> Install-Package Flurl.Http
or just the stand-alone URL builder:
或者只是独立的 URL 构建器:
PM> Install-Package Flurl
PM> Install-Package Flurl