Reputation: 44832
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
Upvotes: 8
Views: 3652
Reputation: 3584
// 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/
Upvotes: 0
Reputation: 35407
Here's a similar question which links to two third party libraries:
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
.
Upvotes: 1
Reputation: 499352
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.
Upvotes: 7