C#Url Builder类

我经常最终为System.Uri推出自己的包装/扩展方法,并且想知道是否有人知道一个好的开源实现。 我最想做的是解析查询字符串参数,构建一个新的查询字符串(这是键),并替换页面名称。 有什么好的,或者System.Uri对你好吗?

BradVin的QueryString Builder类很好。 流畅的界面和对加密的支持。

在CodeProject上查看这个UrlBuilder类也是值得的。 与System.UriBuilder类似,更好地支持使用QueryString。

Flurl [披露:我是作者]是一个流畅的URL构建器,如下所示:

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

如果您正在构建URL以便调用它们, Flurl.Http是一个配套库,可以让您从流畅的链中执行HTTP:

 await "https://api.mysite.com" .AppendPathSegment("person") .SetQueryParams(new { ap_key = "my-key" }) .WithOAuthBearerToken("MyToken") .PostJsonAsync(new { first_name = firstName, last_name = lastName }); 

获取NuGet的完整包:

PM> Install-Package Flurl.Http

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

PM> Install-Package Flurl

正如你所说,我们确实使用了我们自己的替代Uri类,它部分基于Uri。 但是,我认为有一个重要的区别 – System.Uri通常是不可改变的 – 或者更确切地说,是不可改变的行为。 一旦出现,它代表一个精确的通用位置/资源端点。 如果需要描述其他位置,则应创建新的Uri,而不是更改现有的Uri。

有一个专门生产Uri的独立课程: UriBuilder 。

System.UriSystem.UriBuilder ,你究竟有哪两个function?

  ///  /// The arguments must be like: varName1, varValue1, varName2, varValue2 and so on. /// Empty names will be not be added to the result. /// Returns a string of the form varName1=varValue1&varName2=varValue2... ///  public static string BuildQueryString(params string[] strings) { Debug.Assert(0 == strings.GetLength(0) % 2); StringBuilder builder = new StringBuilder(50); bool isName = true; bool isEmptyName = false; foreach (string crtString in strings) { isEmptyName = (isName && string.IsNullOrEmpty(crtString)) || (!isName && isEmptyName); if (!isEmptyName) { builder.Append(HttpUtility.UrlEncode(crtString)); if (isName) builder.Append("="); else builder.Append("&"); } isName = !isName; } return builder.ToString(); } 

CodePlex上有一个非常好的新开源项目,允许您读取,写入,加密Uris等等。 去看一下!

http://querystrings.codeplex.com

我不确定你要做什么(例子会有所帮助),但听起来你正试图在ASP.NET中获得Apache的mod_rewrite的一些function。

MSDN上有一篇关于此的文章 。