Why is HttpUtility.UrlPathEncode marked as "do not use"?
Asked Answered
M

2

8

Why does the documentation of .NET for HttpUtility.UrlPathEncode for .NET 4.5 state

Do not use; intended only for browser compatibility. Use UrlEncode.

UrlEncode does not do the same, it encodes a string for the parameter part of a URL, not for the path part. Is there a better way to encode a string for the path part and why shouldn't I use this function, which is in the framework since 1.1 and works?

Mythical answered 20/11, 2013 at 10:56 Comment(2)
"can be used to encode the entire URL, including query-string values." But UrlEncode doesn't work for relative URLs, at least if the do not have parameters. it encodes spaces as + and also encodes the slashes in the path.Mythical
I'm guessing .Net detects a browser which has limited/no support for unicode characters in the path and encodes them to avoid problems, but I'd love to know for sure...Cristie
E
2

based on MSDN, they recommend to use UrlEncode to grantee that it is working for all platforms and browsers

You can encode a URL using with the UrlEncode method or the UrlPathEncode method. However, the methods return different results. The UrlEncode method converts each space character to a plus character (+). The UrlPathEncode method converts each space character into the string "%20", which represents a space in hexadecimal notation. Use the UrlPathEncode method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.

Also UrlEncode is using UTF-8 encoding so if you are sending query string in different language like Arabic you should use UrlEncode

Echo answered 14/5, 2015 at 11:9 Comment(0)
A
0

Use Uri.EscapeUriString if you want encode a path of a URL. HttpUtility.UrlEncode is for query parameters and encode also slashes which is wrong for a path.

Adeliaadelice answered 14/1, 2019 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.