Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UriBuilder.Query

I found a strange behavior UriBuilder in .NET

Senario 1:

 Dim uri As New UriBuilder("http://www.test/login.aspx")
 uri.Query = "?test=Test"
 Dim url As String = uri.ToString()

After this code is run the url string contains "http://www.test/login.aspx??test=Test"

Solution was to not add the ?.

Senario 2:

 Dim uri As New UriBuilder("http://www.test/login.aspx?test=123")
 uri.Query += "&abc=Test"
 Dim url As String = uri.ToString()

After that code is run we yet again have two ? "http://www.test:80/login.aspx??test=123&abc=Test".

So am I doing some thing wrong when using the uri builder?

like image 231
Peter Avatar asked Jun 18 '12 12:06

Peter


People also ask

What is UriBuilder in Java?

public abstract class UriBuilder extends Object. URI template-aware utility class for building URIs from their components. See Path. value() for an explanation of URI templates.

What is UriBuilder C#?

UriBuilder(String, String, Int32, String, String) Initializes a new instance of the UriBuilder class with the specified scheme, host, port number, path, and query string or fragment identifier. UriBuilder(Uri) Initializes a new instance of the UriBuilder class with the specified Uri instance.

How do I add a parameter to a query string?

Add a WHERE clause that contains the fields you want to add parameters to. If a WHERE clause already exists, check to see whether the fields you want to add parameters to are already in the clause. If they aren't, add them. Note that you need to add the same filter to each section of the query.

What is appendQueryParameter?

appendQueryParameter(String key, String value) Encodes the key and value and then appends the parameter to the query string. Uri.Builder. authority(String authority) Encodes and sets the authority.


1 Answers

The following example sets the Query property.

   UriBuilder baseUri = new UriBuilder("http://www.contoso.com/default.aspx?Param1=7890");
   string queryToAppend = "param2=1234";

   if (baseUri.Query != null && baseUri.Query.Length > 1)
       baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; 
   else
       baseUri.Query = queryToAppend;

The first char ? is not necessary.

More info: http://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx

like image 196
Autociudad Avatar answered Oct 04 '22 05:10

Autociudad