8

I was wondering if .NET had any class used to ease URL generation, similar to Path.Combine but for URLs.

Example of functionality I'm looking for:

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
Thomas Bonini
  • 42,536
  • 29
  • 119
  • 156
  • possible duplicate of [C# Url Builder Class](http://stackoverflow.com/questions/1759881/c-sharp-url-builder-class) – jheddings Nov 10 '12 at 16:23

3 Answers3

7

I believe you are looking for the UriBuilder class.

Provides a custom constructor for uniform resource identifiers (URIs) and modifies URIs for the Uri class.

Oded
  • 477,625
  • 97
  • 867
  • 998
1

Here's a similar question which links to two third party libraries:

C# Url Builder Class

As far as I know, there isn't anything "out-of-the-box" in .NET that allows one a fluent interface to construct the Url and QueryString.

Community
  • 1
  • 1
Alex
  • 34,121
  • 5
  • 74
  • 88
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/
Rashedul.Rubel
  • 2,681
  • 21
  • 33