9

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?

jrummell
  • 42,637
  • 17
  • 112
  • 171
Peter
  • 37,042
  • 39
  • 142
  • 198
  • 2
    According to a comment on the [MSDN docs](http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx) for that class, this bug appears if you set the query property more than once. Having just looked in a decompiler, the setter of `Query` always prepends a leading `?` if the value being set is not empty. – adrianbanks Jun 18 '12 at 12:54
  • ok how horrible, how come they haven't fixed this?, any way post your comment as answer and i will mark it as one! by doing the following i solved my issue uri.Query = uri.Query.Substring(1) + "&abc=Test" – Peter Jun 18 '12 at 13:00

2 Answers2

9

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

Florent
  • 12,310
  • 10
  • 49
  • 58
Autociudad
  • 93
  • 1
  • 4
7

According to a comment on the MSDN docs for that class, this bug appears if you set the query property more than once.

Having just looked in a decompiler, the setter of Query always prepends a leading ? if the value being set is not empty.

adrianbanks
  • 81,306
  • 22
  • 176
  • 206