In a recent project, I had the pleasure of troubleshooting a bug that involved images not loading when spaces were in the filename. I thought "What a simple issue, I'll UrlEncode()
it!" But, NAY! Simply using UrlEncode()
didn't resolve the problem.
The new problem was the HttpUtilities.UrlEncode()
method switched spaces () to plusses (
+
) instead of %20
like the browser wanted. So file+image+name.jpg
would return not-found while file%20image%20name.jpg
was found correctly.
Thankfully, a coworker pointed out HttpUtilities.UrlPathEncode()
to me which uses %20
for spaces instead of +
.
WHY are there two ways of handling Url encoding? WHY are there two commands that behave so differently?
So in a URL you have the path and then a ? and then the parameters (i.e. http://some_path/page.aspx?parameters). URL paths encode spaces differently then the url parameters, that's why there is the two versions. For a long time spaces were not valid in a URL, but were in in the parameters.
In other words the formatting urls has changed over time. For a long time only ANSI chars could be in a URL too.
UrlEncode is useful for use with a QueryString as browsers tend to use a
+
here in place of a space when submitting forms with theGET
method.UrlPathEncode simply replaces all characters that cannot be used within a URL, such as
<
,>
and.
Both MSDN links include this quote: