23

I need to redirect to a url passing a parameter as a query string.

This can include an Ampersand in the value. such as

string value = "This & That";
Response.Redirect("http://www.example.com/?Value=" + Server.UrlEncode(value));

This however returns http://www.example.com/?Value=This+&+That

What should I be using to encode this string?

EDIT: Thanks Luke for pointing out the obvious, the code does indeed work correctly. I Apologise, my question was not a valid question after all!

The page I was going to had a lot of old legacy code which is apparently doing some kinda of encoding and decoding itself making it appear as if my urlencode was not working.

My solution unfortunately is to completely drop use of an & until the code in question can be re-written. Don't you just hate old code!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Robin Day
  • 100,552
  • 23
  • 116
  • 167

7 Answers7

24

The documentation suggests that Server.UrlEncode should handle ampersands correctly.

I've just tested your exact code and the returned string was correctly encoded:

http://www.example.com/?Value=This+%26+That

Cœur
  • 37,241
  • 25
  • 195
  • 267
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • You are totally correct! The page I was using was going to had a lot of old legacy code which is apprently doing some kinda of encoding and decoding itself making it appear as if my urlencode was not working. This works correctly.. as it should!! – Robin Day Feb 18 '09 at 18:42
  • 2
    In situations where you don't have a Server variable, you can also access the urlencode/urldecode methods through System.Web.HttpUtility – Adam Lassek Feb 18 '09 at 18:47
  • 1
    Note for other people visiting this page; if you're not within an ASP application (and therefore haven't got access to `Server`) you can use `System.Web.HttpUtility.UrlEncode`. – Doctor Jones Jan 05 '12 at 10:22
  • 2
    Also note that `Server.UrlEncode`, `System.Web.HttpUtility.UrlEncode`, `System.Uri.EscapeDataString`, and `System.Uri.EscapeUriString` do not agree on how to encode things. Don't expect them to have the same outputs, and be careful when trying to compare or decode things especially when special characters are involved. – TheAtomicOption Aug 04 '19 at 23:39
18

Technically doing:

value = value.Replace("&", "%26") 

will do the trick.

EDIT: There seem to be some tricky issues with the whole UrlEncode/HttpEncode methods that don't quite do the trick. I wrote up a simple method a while back that may come in handy. This should cover all the major encoding issues, and its easy to write a "desanitizer" as well.

Protected Function SanitizeURLString(ByVal RawURLParameter As String) As String

      Dim Results As String

      Results = RawURLParameter    

      Results = Results.Replace("%", "%25")
      Results = Results.Replace("<", "%3C")
      Results = Results.Replace(">", "%3E")
      Results = Results.Replace("#", "%23")
      Results = Results.Replace("{", "%7B")
      Results = Results.Replace("}", "%7D")
      Results = Results.Replace("|", "%7C")
      Results = Results.Replace("\", "%5C")
      Results = Results.Replace("^", "%5E")
      Results = Results.Replace("~", "%7E")
      Results = Results.Replace("[", "%5B")
      Results = Results.Replace("]", "%5D")
      Results = Results.Replace("`", "%60")
      Results = Results.Replace(";", "%3B")
      Results = Results.Replace("/", "%2F")
      Results = Results.Replace("?", "%3F")
      Results = Results.Replace(":", "%3A")
      Results = Results.Replace("@", "%40")
      Results = Results.Replace("=", "%3D")
      Results = Results.Replace("&", "%26")
      Results = Results.Replace("$", "%24")

      Return Results

End Function
Doctor Jones
  • 21,196
  • 13
  • 77
  • 99
Dillie-O
  • 29,277
  • 14
  • 101
  • 140
  • Agreed. "&" is a reserved character in a URL, and so wouldn't be URL encoded. – Zhaph - Ben Duguid Feb 18 '09 at 17:14
  • 1
    Technically, you only need to 'Sanitize' forward slashes, ampersands, and question marks. URLEncode will do the rest. – BC. Feb 18 '09 at 17:19
  • 1
    For some reason I thought spaces had to be re-encoded to the %20 and not +, or can it go either way? – Dillie-O Feb 18 '09 at 21:15
  • 1
    @Dillie-O, The recommended encoding for space is now "%20", but historically "+" was used (see page 7 of http://tools.ietf.org/html/rfc1630 for more info). Pretty much all browsers/servers etc will handle either encoding, though I've no idea why .NET still uses the obsolete "+". – LukeH Feb 18 '09 at 23:48
  • 8
    Wouldn't Results = Results.Replace("%", "%25") screw up the ones above it. – big_tommy_7bb Aug 03 '11 at 09:52
  • @LukeH `string path = Uri.EscapeUriString(path);` will escape spaces to "%20". It doesn't handle ampersands or colons, though. The `System.Web.HttpUtility.UrlEncode` will use "+" as you say, though. – vapcguy Nov 08 '18 at 19:03
  • @big_tommy_7bb Looks like that line replacing the `%` with `%25` was at the top - which should've prevented things getting trampled on - but I saw it actually did have a problem - apparently `.Replace()` isn't synchronous and it won't wait before going to the next line, converting say, spaces, to `%20`, which then changes to `%2520` when that first line catches up. It means you'd want to pull that `Results = Results.Replace("%", "%25")` line out and do that ahead of calling this function, altogether. – vapcguy Nov 08 '18 at 19:31
3

In .net core ver 2.1 ( late 2018 ) I was able to use the following:

System.Web.HttpUtility.UrlEncode(string_to_encode)
Rekshino
  • 6,954
  • 2
  • 19
  • 44
Eli
  • 1,670
  • 1
  • 20
  • 23
2

You must use Server.UrlEncode(string containing the ampersand).

I've just tested it and the returned query string was correctly encoded and then decoded.

HttpUtility didn't work for this operation.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Omgee Cares
  • 427
  • 2
  • 5
  • 12
2

Another character that needs escaping is the apostrophe. Replace it with %27.

string url = Server.UrlEncode(value).Replace("'", "%27);

HttpUtility.UrlEncode() And Server.UrlEncode() do not replace this character along with a few others for backwards compatibility with other .Net Frameworks. See this microsoft article for details: http://connect.microsoft.com/VisualStudio/feedback/details/214349/httputility-urlencode-does-not-encode-apostrophe

goku_da_master
  • 4,257
  • 1
  • 41
  • 43
2

this is correct however if you have several parameters in the query string.

for example : &firstname=bob&secondName="Tracy and John"

tigerdev
  • 21
  • 1
1

And if you are getting a value from a GridView the & ampersand may very well be showing up as "&amp;":

row.Cells[4].Text.ToString() = xxxx&amp;

So in this case you will want to use:

.Replace("&amp;", "%26")
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Kinch
  • 11
  • 1