ASP.NET Processing: URI

I am writing a method that, for example, gives 1 and hello should return http://something.com/?something=1&hello=en .

I could easily hack this together, but what abstraction functions do ASP.NET 3.5 do to create the URI? I would like something like:

 URI uri = new URI("~/Hello.aspx"); // Eg ResolveUrl is used here uri.QueryString.Set("something", "1"); uri.QueryString.Set("hello", "en"); return uri.ToString(); // /Hello.aspx?something=1&hello=en 

I found a Uri class that sounds very relevant, but I can't find anything that really does the above. Any ideas?

(For what this value is, the order of the parameters does not matter to me.)

+4
source share
6 answers

Edited to fix mass invalid code

Based on this answer to a similar question, you can easily do something like:

 UriBuilder ub = new UriBuilder(); // You might want to take more care here, and set the host, scheme and port too ub.Path = ResolveUrl("~/hello.aspx"); // Assumes we're on a page or control. // Using var gets around internal nature of HttpValueCollection var coll = HttpUtility.ParseQueryString(string.Empty); coll["something"] = "1"; coll["hello"] = "en"; ub.Query = coll.ToString(); return ub.ToString(); // This returned the following on the VS development server: // http://localhost/Hello.aspx?something=1&hello=en 

This will also be a urlencode collection, therefore:

 coll["Something"] = "1"; coll["hello"] = "en&that"; 

It will display:

 Something=1&hello=en%26that 
+13
source

I don’t know anything yet. Thus, everyone has their own implementation.

Example from LinqToTwitter .

  internal static string BuildQueryString(IEnumerable<KeyValuePair<string, string>> parameters) { if (parameters == null) { throw new ArgumentNullException("parameters"); } StringBuilder builder = new StringBuilder(); foreach (var pair in parameters.Where(p => !string.IsNullOrEmpty(p.Value))) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(Uri.EscapeDataString(pair.Key)); builder.Append("="); builder.Append(Uri.EscapeDataString(pair.Value)); } return builder.ToString(); } 

UPDATE:

You can also create an extension method:

 public static UriBuilder AddArgument(this UriBuilder builder, string key, string value) { #region Contract Contract.Requires(builder != null); Contract.Requires(key != null); Contract.Requires(value != null); #endregion var query = builder.Query; if (query.Length > 0) { query = query.Substring(1) + "&"; } query += Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(value); builder.Query = query; return builder; } 

And use:

 var b = new UriBuilder(); b.AddArgument("test", "test"); 

Please note that everything here is not verified.

+4
source

Just combined answers =>

 public static class UriBuilderExtensions { public static void AddQueryArgument(this UriBuilder b, string key, string value) { key = Uri.EscapeDataString(key); value = Uri.EscapeDataString(value); var x = HttpUtility.ParseQueryString(b.Query); if (x.AllKeys.Contains(key)) throw new ArgumentNullException ("Key '{0}' already exists!".FormatWith(key)); x.Add(key, value); b.Query = x.ToString(); } public static void EditQueryArgument(this UriBuilder b, string key, string value) { key = Uri.EscapeDataString(key); value = Uri.EscapeDataString(value); var x = HttpUtility.ParseQueryString(b.Query); if (x.AllKeys.Contains(key)) x[key] = value; else throw new ArgumentNullException ("Key '{0}' does not exists!".FormatWith(key)); b.Query = x.ToString(); } public static void AddOrEditQueryArgument(this UriBuilder b, string key, string value) { key = Uri.EscapeDataString(key); value = Uri.EscapeDataString(value); var x = HttpUtility.ParseQueryString(b.Query); if (x.AllKeys.Contains(key)) x[key] = value; else x.Add(key, value); b.Query = x.ToString(); } public static void DeleteQueryArgument(this UriBuilder b, string key) { key = Uri.EscapeDataString(key); var x = HttpUtility.ParseQueryString(b.Query); if (x.AllKeys.Contains(key)) x.Remove(key); b.Query = x.ToString(); } } 

The semicircular code. But it should work quite well.

+3
source

Here is also the UriBuilder class

0
source

This is what you might like - recently at work I was looking for a way to "type" frequently used URL query string variables and developed this interface this way:

  'Represent a named parameter that is passed from page-to-page via a range of methods- query strings, HTTP contexts, cookies, session, etc. Public Interface INamedParam 'A key that uniquely identfies this parameter in any HTTP value collection (query string, context, session, etc.) ReadOnly Property Key() As String 'The default value of the paramter. ReadOnly Property DefaultValue() As Object End Interface 

Then you can implement this interface to describe the query string parameter, such an implementation for your "Hello" parameter might look like this:

 Public Class HelloParam Implements INamedParam Public ReadOnly Property DefaultValue() As Object Implements INamedParam.DefaultValue Get Return "0" End Get End Property Public ReadOnly Property Key() As String Implements INamedParam.Key Get Return "hello" End Get End Property End Class 

I developed a small (and very, very simple) class for creating URLs using these strongly typed parameters:

 Public Class ParametrizedHttpUrlBuilder Private _RelativePath As String Private _QueryString As String Sub New(ByVal relativePath As String) _RelativePath = relativePath _QueryString = "" End Sub Public Sub AddQueryParameterValue(ByVal param As INamedParam, ByVal value As Object) Dim sb As New Text.StringBuilder(30) If _QueryString.Length > 0 Then sb.Append("&") End If sb.AppendFormat("{0}={1}", param.Key, value.ToString()) _QueryString &= sb.ToString() End Sub Public Property RelativePath() As String Get Return _RelativePath End Get Set(ByVal value As String) If value Is Nothing Then _RelativePath = "" End If _RelativePath = value End Set End Property Public ReadOnly Property Query() As String Get Return _QueryString End Get End Property Public ReadOnly Property PathAndQuery() As String Get Return _RelativePath & "?" & _QueryString End Get End Property End Class 
0
source

Here is my version (requires calling .NET4 or ToArray () on Select)

 var items = new Dictionary<string,string> { { "Name", "Will" }, { "Age", "99" }}; String query = String.Join("&", items.Select(i => String.Concat(i.Key, "=", i.Value))); 

I thought that using the Dictionary could mean that the elements could be reordered, but in fact this does not happen in the experiments here - I'm not sure what that means.

0
source

All Articles