.NET 4.5桌面应用中匹配urlencoder.org的C#编码方法
Matching urlencoder.org's URL Encoding in .NET 4.5
First, let's break down the key differences between .NET's default encoding methods and the result you got from urlencoder.org:
- Space handling: urlencoder.org uses
%20for spaces, while most .NET methods use+(following theapplication/x-www-form-urlencodedstandard, intended for form data rather than raw URL paths). - Character encoding: The
áin your string is encoded as%C3%A1(UTF-8) by urlencoder.org, but your .NET tests returned%E1(ISO-8859-1/Latin-1) — this suggests a mismatch in the encoding being used for the character. - Case preservation: urlencoder.org keeps your original casing (e.g.,
DestaysDe), while your .NET results showed lowercasede— this is likely a test input inconsistency, as .NET's encoding methods don't modify string casing.
To replicate urlencoder.org's behavior in .NET 4.5, you'll need a custom method that strictly uses UTF-8 encoding and replaces spaces with %20 instead of +. Here's a reliable implementation:
using System.Text; public static class CustomUrlEncoder { public static string EncodeLikeUrlEncoderOrg(string input) { if (string.IsNullOrWhiteSpace(input)) return input; byte[] utf8Bytes = Encoding.UTF8.GetBytes(input); StringBuilder encodedBuilder = new StringBuilder(); foreach (byte b in utf8Bytes) { // Keep unreserved characters as-is (per RFC 3986) if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == '-' || b == '_' || b == '.' || b == '~') { encodedBuilder.Append((char)b); } else { // Encode all other bytes as %XX in uppercase encodedBuilder.Append($"%{b:X2}"); } } return encodedBuilder.ToString(); } }
How to use it:
string originalString = "Radio Signal Gabriel Moraes,fernando De Sá"; string encodedString = CustomUrlEncoder.EncodeLikeUrlEncoderOrg(originalString); // Result: Radio%20Signal%20Gabriel%20Moraes%2Cfernando%20De%20S%C3%A1
Why your existing .NET methods didn't match:
HttpUtility.UrlEncode: Uses+for spaces and defaults to the system's default encoding (which might be ISO-8859-1 on your machine) unless you explicitly specify UTF-8. Even with UTF-8 specified, it still uses+instead of%20.Uri.EscapeDataString: In .NET 4.5, this should use UTF-8 and encode spaces as%20, but if your input string'sáwas stored as an ISO-8859-1 byte instead of a UnicodeU+00E1character, it would still encode to%E1. Double-check that your original string uses proper Unicode characters.Uri.EscapeUriString: This method is designed for escaping entire URIs, not individual segments, so it may skip encoding certain characters that urlencoder.org handles.
内容的提问来源于stack exchange,提问作者Keith Boynton
相关产品推荐
相关产品推荐

