2012-11-10 43 views
8

我想知道.NET是否有任何类用于简化URL生成,类似于Path.Combine但是用于URL。.NET中的URL字符串生成

的功能的示例我在寻找:

string url = ClassName.Combine("http://www.google.com", "index") 
      .AddQueryParam("search", "hello world").AddQueryParam("pagenum", 3); 
// Result: http://www.google.com/index?search=hello%20world&pagenum=3 
+0

可能重复的[C#地址生成器类(http://stackoverflow.com/questions/1759881/c-sharp-url-builder-class) – jheddings

回答

7

我相信你正在寻找UriBuilder类。

为统一资源标识符(URI)提供自定义构造函数,并修改Uri类的URI。

1

这里有一个类似的问题,哪个环节两个第三方库:

C# Url Builder Class

据我所知,目前还没有什么“出的即装即用”的。 NET,它允许流畅的接口构建UrlQueryString

0
// In webform code behind: 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Collections.Specialized; 

namespace testURL 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     protected void Button1_Click(object sender, EventArgs e) 
     { 
      NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty); 

      queryString["firstKey"] = "a"; 
      queryString["SecondKey"] = "b"; 

      string url=GenerateURL(queryString); // call function to get the url 
     } 

     private string GenerateURL(NameValueCollection nvc) 
     { 
      return "index.aspx?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key])))); 
     } 

    } 
} 


    // To get information to generate URL in MVC please check the following tutorial: 
    http://net.tutsplus.com/tutorials/generating-traditional-urls-with-asp-net-mvc3/