SoFunction
Updated on 2025-03-09

How to convert URL spaces in the web

Look at the URL, converting spaces into "+" sign, and then starting to solve the bug when you find the reason.
Quote:

Copy the codeThe code is as follows:

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

Replace replacement, although the problem is solved, this is not a good way. If the folder or file name contains the "+" sign, it will cause another bug to occur.
Best Solution:

Using the UrlPathEncode method, perform the following steps:

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

2. Encode non-spaces so that a subset of the first 128 ASCII characters is used in the resulting encoded string. All character values ​​for Unicode are 128 and higher, or 32 and smaller, enter in the URL.

3. Enter space as %20.

Use the UrlEncode method or the UrlPathEncode method to enter a URL. However, the method returns different results. The UrlEncode method converts each space character to a plus (+) character. The UrlPathEncode method converts each space character to a string %20, a space represented in hexadecimal notation. Use the UrlPathEncode method when encoding the path part of the URL to ensure a consistent decoded URL, regardless of the platform or browser that performed the decoding. When you use the UrlPathEncode method, the query string value is not entered. Therefore, any value (?) that can be passed in the string will not be entered. If the URL must be passed, when querying the string, the UrlEncode method is used.

I saw that many pages in the project use the Replace method, and after query, all replaced them with UrlPathEncode to reduce the occurrence of more bugs.