Web URL space conversion method

  • 2020-06-07 04:22:56
  • OfStack

See URL is HttpUtility.UrlEncode converts Spaces to "+", find the reason and work on Bug.

  fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8); 
  fileName = fileName.Replace("+", "%20"); 

With Replace replacement, the problem is solved, but this is not a good solution. If the folder or filename contains a +, another Bug will occur.
Best solution:

Use the HttpUtility.UrlPathEncode, UrlPathEncode method to perform the following steps:

1. Apply the encoding logic of the UrlPathEncode method only to the path part of URL (not including the query string). This method assumes that URL is encoded as the ES22en-8 string.

2. Encode non-whitespace to use a subset of the first 128 ASCII characters in the resulting encoded string. All character values of Unicode are 128 and higher, or 32 and smaller, entered in URL.

3. Enter the space as %20.

Using the UrlEncode method or the UrlPathEncode method, you can enter URL. However, the method returns a different result. The UrlEncode method converts each space character to a plus (+) character. The UrlPathEncode method converts each space character to a string %20, representing 1 space in hex notation. Use the UrlPathEncode method when encoding the path part of URL to ensure that the 1 sent URL has been decoded, regardless of the platform or browser on which the decoding is performed. When you use the UrlPathEncode method, the query string value is not entered. Therefore, any value (?) that can be passed by a question mark. In the string, no input will be made. If URL must be passed, the UrlEncode method is used when querying the string.

See that many of the pages in the project are using Replace, and replace them all with UrlPathEncode after the query to reduce the occurrence of Bug.

Related articles: