In ASP.NET, why does UrlEncode () AND UrlPathEncode () exist?

In a recent project, I had the pleasure of fixing errors related to non-loading images when there were spaces in the file name. I thought: "What a simple problem, I will do it!" But, NAY! Just using UrlEncode() did not solve the problem.

The new issue was that the HttpUtilities.UrlEncode() switch HttpUtilities.UrlEncode() were mixed up ( ) on the pluses ( + ) instead of %20 , as in the browser. Therefore, file+image+name.jpg will be returned not found, and file%20image%20name.jpg will be found correctly.

Fortunately, a colleague pointed me to HttpUtilities.UrlPathEncode() at me, which uses %20 for spaces instead of + .

WHY are there two ways to handle Url encoding? WHY are there two teams that behave differently?

+7
source share
2 answers

UrlEncode is useful for use with QueryString, as browsers usually use + instead of space when submitting forms using GET .

UrlPathEncode simply replaces all characters that cannot be used in the URL, such as < , > and .

Both MSDN links include this quote:

You can encode the URL using the UrlEncode method or the UrlPathEncode method. However, methods return different results. The UrlEncode method converts each space into a plus sign (+). The UrlPathEncode method converts each whitespace character to the string "% 20", which is a space in the hexadecimal system. use the UrlPathEncode method when encoding part of the URL path to ensure a consistent decoded URL, regardless of which platform or browser is decoding.

+9
source

So there is a path in the url and then? and then the parameters (i.e. http: //some_path/page.aspx? parameters ). URL paths encode spaces differently and then URL parameters, so there are two versions. For a long time, spaces were not valid in the URL, but were in the parameters.

In other words, formatting URLs have changed over time. Over time, only the ANSI URL can also be in the URL.

+2
source

All Articles