Search code examples
.neturibuilder

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?


Solution

  • 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.