2012-11-10 35 views
8

Tôi đã tự hỏi nếu .NET có bất kỳ lớp nào được sử dụng để dễ dàng tạo URL, tương tự như Path.Combine nhưng đối với URL.Tạo chuỗi URL trong .NET

Ví dụ về chức năng Tôi đang tìm:

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

thể trùng lặp của [C# Url Builder Lớp] (http://stackoverflow.com/questions/1759881/c-sharp-url-builder-class) – jheddings

Trả lời

7

Tôi tin rằng bạn đang tìm kiếm lớp UriBuilder.

Cung cấp hàm tạo tùy chỉnh cho số nhận dạng tài nguyên đồng nhất (URI) và sửa đổi URI cho lớp Uri.

1

Dưới đây là một câu hỏi tương tự mà liên kết với hai thư viện của bên thứ ba:

C# Url Builder Class

Theo như tôi biết, không có bất cứ điều gì "out-of-the-box" trong. NET cho phép một giao diện thông thạo để xây dựng 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/