How to encode query string space with %20 instead of + ?
Because System.Web HttpUtility.UrlEncode() gives the space with +.
Asked
Active
Viewed 4.5k times
54
GeralexGR
- 2,059
- 5
- 20
- 27
Sharath Kumar K J
- 623
- 1
- 6
- 11
-
In modern .Net Core UrlEncode uses %20 – Michael Freidgeim Feb 19 '20 at 21:46
-
5@MichaelFreidgeim might you be a little more specific than "modern" please - I am running with target framework netcoreapp3.1 and HttpUtility.UrlEncode(somestring) is giving me + instead of %20 – MemeDeveloper Jan 19 '21 at 20:37
1 Answers
76
https://msdn.microsoft.com/en-us/library/system.uri.escapeuristring(v=vs.110).aspx
var encoded = Uri.EscapeUriString("How to encode");
OUTPUT:
How%20to%20encode
Manfred Radlwimmer
- 12,826
- 13
- 52
- 59
L.B
- 110,417
- 19
- 170
- 215
-
34You may want to use Uri.EscapeDataString() Because Uri string will get spaces but will not encode other characters. Example '#' – Robert Koernke Jun 19 '19 at 20:07
-
1Uri.EscapeUriString has been marked as obsolete as of 9/15/2021 since it "can corrupt the Uri string in some cases." As @Robert Koernke said, the new recommended approach by Microsoft is Uri.EscapeDataString() – arrakis90 Apr 04 '22 at 16:35