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
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.