HttpUtility.UrlEncode Does not encode spaces properly
January 14th, 2005
I realized a while back that HttpUtility.UrlEncode does not properly encode spaces for URLs. It encodes a space as a “+“ which most browsers do not interpret as a space for the obvious reason that + is actually a valid character for a filename. So to work around the bug we wrote the following:
| public static string URLEncode(string str) { return System.Web.HttpUtility.UrlEncode( str ).Replace(”+”,”%20″); } |
It’s interesting to note that HttpUtility.UrlPathEncode does properly encode the space but fails to encode other critical charcters like & and ?.

In my small experiments I have seen the following;
string e = “<script lang=’javascript’ />”;
string e1 = HttpUtility.HtmlEncode(e);
string e2 = HttpUtility.UrlEncode(e);
string e3 = HttpUtility.UrlPathEncode(e);
string e4 = HttpUtility.HtmlAttributeEncode(e);
and then you get the following results;
e1 = “<script lang=’javascript’ />”
e2 = “%3cscript+lang%3d’javascript’+%2f%3e”
e3 = “<script%20lang=’javascript’%20/>”
e4 = “<script lang=’javascript’ />”
which means you might have to employ to encode;
string e5 = HttpUtility.UrlEncode(HttpUtility.UrlPathEncode(a));
and eventually
string d5 = HttpUtility.UrlDecode(HttpUtility.HtmlDecode(e5))
which gives
e5 = “%3cscript%2520lang%3d’javascript’%2520%2f%3e”
d5 = “<script lang=’javascript’ />”
to get the “best” result… (I doubt it too..)
Sorry for the cryptic writing…
actually, the string “d5″ results in this, which is a lot different than above:
“<script%20lang=’javascript’%20/>”
…which takes us back to the start…
when you are doing HttpUtility.UrlDecode(); if decodes both urlEncode(), and urlPathEncode(). So, d5 should be:
string d5 = HttpUtility.UrlDecode(e5)
it decodes both space and other chars that were encoded by both method.