405

我有一个应用程序,它向 VB 论坛软件发送一个 POST 请求并让某人登录(不设置 cookie 或任何东西)。

用户登录后,我会创建一个变量,在他们的本地机器上创建一个路径。

c:\tempfolder\日期\用户名

问题是一些用户名抛出“非法字符”异常。例如,如果我的用户名是mas|fenix它会抛出异常..

Path.Combine( _      
  Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), _
  DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username)

我不想从字符串中删除它,但是通过服务器上的 FTP 创建了一个带有用户名的文件夹。这引出了我的第二个问题。如果我在服务器上创建一个文件夹,我可以留下“非法字符”吗?我只问这个是因为服务器是基于 Linux 的,我不确定 Linux 是否接受它。

编辑:似乎 URL 编码不是我想要的。这就是我想要做的:

old username = mas|fenix
new username = mas%xxfenix

其中 %xx 是 ASCII 值或任何其他可以轻松识别字符的值。

4

13 回答 13

625

我一直在试验 .NET 为 URL 编码提供的各种方法。也许下表会很有用(作为我编写的测试应用程序的输出):

Unencoded UrlEncoded UrlEncodedUnicode UrlPathEncoded EscapedDataString EscapedUriString HtmlEncoded HtmlAttributeEncoded HexEscaped
A         A          A                 A              A                 A                A           A                    %41
B         B          B                 B              B                 B                B           B                    %42

a         a          a                 a              a                 a                a           a                    %61
b         b          b                 b              b                 b                b           b                    %62

0         0          0                 0              0                 0                0           0                    %30
1         1          1                 1              1                 1                1           1                    %31

[space]   +          +                 %20            %20               %20              [space]     [space]              %20
!         !          !                 !              !                 !                !           !                    %21
"         %22        %22               "              %22               %22              "      "               %22
#         %23        %23               #              %23               #                #           #                    %23
$         %24        %24               $              %24               $                $           $                    %24
%         %25        %25               %              %25               %25              %           %                    %25
&         %26        %26               &              %26               &                &       &                %26
'         %27        %27               '              '                 '                '       '                %27
(         (          (                 (              (                 (                (           (                    %28
)         )          )                 )              )                 )                )           )                    %29
*         *          *                 *              %2A               *                *           *                    %2A
+         %2b        %2b               +              %2B               +                +           +                    %2B
,         %2c        %2c               ,              %2C               ,                ,           ,                    %2C
-         -          -                 -              -                 -                -           -                    %2D
.         .          .                 .              .                 .                .           .                    %2E
/         %2f        %2f               /              %2F               /                /           /                    %2F
:         %3a        %3a               :              %3A               :                :           :                    %3A
;         %3b        %3b               ;              %3B               ;                ;           ;                    %3B
<         %3c        %3c               <              %3C               %3C              &lt;        &lt;                 %3C
=         %3d        %3d               =              %3D               =                =           =                    %3D
>         %3e        %3e               >              %3E               %3E              &gt;        >                    %3E
?         %3f        %3f               ?              %3F               ?                ?           ?                    %3F
@         %40        %40               @              %40               @                @           @                    %40
[         %5b        %5b               [              %5B               %5B              [           [                    %5B
\         %5c        %5c               \              %5C               %5C              \           \                    %5C
]         %5d        %5d               ]              %5D               %5D              ]           ]                    %5D
^         %5e        %5e               ^              %5E               %5E              ^           ^                    %5E
_         _          _                 _              _                 _                _           _                    %5F
`         %60        %60               `              %60               %60              `           `                    %60
{         %7b        %7b               {              %7B               %7B              {           {                    %7B
|         %7c        %7c               |              %7C               %7C              |           |                    %7C
}         %7d        %7d               }              %7D               %7D              }           }                    %7D
~         %7e        %7e               ~              ~                 ~                ~           ~                    %7E

Ā         %c4%80     %u0100            %c4%80         %C4%80            %C4%80           Ā           Ā                    [OoR]
ā         %c4%81     %u0101            %c4%81         %C4%81            %C4%81           ā           ā                    [OoR]
Ē         %c4%92     %u0112            %c4%92         %C4%92            %C4%92           Ē           Ē                    [OoR]
ē         %c4%93     %u0113            %c4%93         %C4%93            %C4%93           ē           ē                    [OoR]
Ī         %c4%aa     %u012a            %c4%aa         %C4%AA            %C4%AA           Ī           Ī                    [OoR]
ī         %c4%ab     %u012b            %c4%ab         %C4%AB            %C4%AB           ī           ī                    [OoR]
Ō         %c5%8c     %u014c            %c5%8c         %C5%8C            %C5%8C           Ō           Ō                    [OoR]
ō         %c5%8d     %u014d            %c5%8d         %C5%8D            %C5%8D           ō           ō                    [OoR]
Ū         %c5%aa     %u016a            %c5%aa         %C5%AA            %C5%AA           Ū           Ū                    [OoR]
ū         %c5%ab     %u016b            %c5%ab         %C5%AB            %C5%AB           ū           ū                    [OoR]

这些列表示编码如下:

  • 网址编码:HttpUtility.UrlEncode

  • UrlEncodedUnicode:HttpUtility.UrlEncodeUnicode

  • UrlPath 编码:HttpUtility.UrlPathEncode

  • 转义数据字符串:Uri.EscapeDataString

  • 转义UriString:Uri.EscapeUriString

  • Html 编码:HttpUtility.HtmlEncode

  • HtmlAttributeEncoded:HttpUtility.HtmlAttributeEncode

  • 十六进制转义:Uri.HexEscape

笔记:

  1. HexEscape只能处理前 255 个字符。因此,它会ArgumentOutOfRange为拉丁 A 扩展字符(例如 Ā)抛出异常。

  2. 该表是在 .NET 4.0 中生成的(请参阅下面的 Levi Botelho 的评论,其中说 .NET 4.5 中的编码略有不同)。

编辑:

我添加了第二个表,其中包含 .NET 4.5 的编码。看到这个答案:https ://stackoverflow.com/a/21771206/216440

编辑2:

由于人们似乎很欣赏这些表格,我想你可能会喜欢生成表格的源代码,所以你可以自己玩。这是一个简单的 C# 控制台应用程序,可以针对 .NET 4.0 或 4.5:

using System;
using System.Collections.Generic;
using System.Text;
// Need to add a Reference to the System.Web assembly.
using System.Web;

namespace UriEncodingDEMO2
{
    class Program
    {
        static void Main(string[] args)
        {
            EncodeStrings();

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.Read();
        }

        public static void EncodeStrings()
        {
            string stringToEncode = "ABCD" + "abcd"
            + "0123" + " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" + "ĀāĒēĪīŌōŪū";

            // Need to set the console encoding to display non-ASCII characters correctly (eg the 
            //  Latin A-Extended characters such as ĀāĒē...).
            Console.OutputEncoding = Encoding.UTF8;

            // Will also need to set the console font (in the console Properties dialog) to a font 
            //  that displays the extended character set correctly.
            // The following fonts all display the extended characters correctly:
            //  Consolas
            //  DejaVu Sana Mono
            //  Lucida Console

            // Also, in the console Properties, set the Screen Buffer Size and the Window Size 
            //  Width properties to at least 140 characters, to display the full width of the 
            //  table that is generated.

            Dictionary<string, Func<string, string>> columnDetails =
                new Dictionary<string, Func<string, string>>();
            columnDetails.Add("Unencoded", (unencodedString => unencodedString));
            columnDetails.Add("UrlEncoded",
                (unencodedString => HttpUtility.UrlEncode(unencodedString)));
            columnDetails.Add("UrlEncodedUnicode",
                (unencodedString => HttpUtility.UrlEncodeUnicode(unencodedString)));
            columnDetails.Add("UrlPathEncoded",
                (unencodedString => HttpUtility.UrlPathEncode(unencodedString)));
            columnDetails.Add("EscapedDataString",
                (unencodedString => Uri.EscapeDataString(unencodedString)));
            columnDetails.Add("EscapedUriString",
                (unencodedString => Uri.EscapeUriString(unencodedString)));
            columnDetails.Add("HtmlEncoded",
                (unencodedString => HttpUtility.HtmlEncode(unencodedString)));
            columnDetails.Add("HtmlAttributeEncoded",
                (unencodedString => HttpUtility.HtmlAttributeEncode(unencodedString)));
            columnDetails.Add("HexEscaped",
                (unencodedString
                    =>
                    {
                        // Uri.HexEscape can only handle the first 255 characters so for the 
                        //  Latin A-Extended characters, such as A, it will throw an 
                        //  ArgumentOutOfRange exception.                       
                        try
                        {
                            return Uri.HexEscape(unencodedString.ToCharArray()[0]);
                        }
                        catch
                        {
                            return "[OoR]";
                        }
                    }));

            char[] charactersToEncode = stringToEncode.ToCharArray();
            string[] stringCharactersToEncode = Array.ConvertAll<char, string>(charactersToEncode,
                (character => character.ToString()));
            DisplayCharacterTable<string>(stringCharactersToEncode, columnDetails);
        }

        private static void DisplayCharacterTable<TUnencoded>(TUnencoded[] unencodedArray,
            Dictionary<string, Func<TUnencoded, string>> mappings)
        {
            foreach (string key in mappings.Keys)
            {
                Console.Write(key.Replace(" ", "[space]") + " ");
            }
            Console.WriteLine();

            foreach (TUnencoded unencodedObject in unencodedArray)
            {
                string stringCharToEncode = unencodedObject.ToString();
                foreach (string columnHeader in mappings.Keys)
                {
                    int columnWidth = columnHeader.Length + 1;
                    Func<TUnencoded, string> encoder = mappings[columnHeader];
                    string encodedString = encoder(unencodedObject);

                    // ASSUMPTION: Column header will always be wider than encoded string.
                    Console.Write(encodedString.Replace(" ", "[space]").PadRight(columnWidth));
                }
                Console.WriteLine();
            }
        }
    }
}

单击此处在 dotnetfiddle.net 上运行代码

于 2012-06-27T23:10:56.053 回答
296

您应该只对用户名或 URL 中可能无效的其他部分进行编码。URL 对 URL 进行编码可能会导致问题,因为如下所示:

string url = HttpUtility.UrlEncode("http://www.google.com/search?q=Example");

将产生

http%3a%2f%2fwww.google.com%2fsearch%3fq%3dExample

这显然不会很好地工作。相反,您应该只对查询字符串中的键/值对的值进行编码,如下所示:

string url = "http://www.google.com/search?q=" + HttpUtility.UrlEncode("Example");

希望这会有所帮助。此外,正如teedyay 所提到的,您仍然需要确保删除非法文件名字符,否则文件系统将不喜欢该路径。

于 2009-02-22T21:29:28.397 回答
220

更好的方法是使用

Uri.EscapeUriString

不参考 .net 4 的完整配置文件。

于 2011-09-15T07:57:11.473 回答
209

编辑:请注意,这个答案现在已经过时了。请参阅下面的 Siarhei Kuchuk 的答案以获得更好的解决方案

UrlEncoding 将执行您在此处的建议。HttpUtility如前所述,使用 C#,您只需使用.

您也可以对非法字符进行正则表达式然后替换,但这会变得更加复杂,因为您必须拥有某种形式的状态机(例如 switch ... case)才能用正确的字符替换。由于UrlEncode这是预先完成的,因此相当容易。

至于 Linux 与 Windows,有些字符在 Linux 中是可接受的,但在 Windows 中是不可接受的,但我不担心,因为文件夹名称可以通过解码 Url 字符串返回,使用UrlDecode,所以你可以往返变化。

于 2009-02-22T20:55:35.497 回答
199

.NET Framework 4.5.NET Standard 1.0 开始,您应该使用WebUtility.UrlEncode. 优于替代品的优势:

  1. 它是 .NET Framework 4.5+、.NET Core 1.0+、.NET Standard 1.0+、UWP 10.0+ 以及所有 Xamarin 平台的一部分。HttpUtility,虽然在早期的 .NET Framework(.NET Framework 1.1+)中可用,但在其他平台上可用的时间要晚得多(.NET Core 2.0+、.NET Standard 2.0+),并且在 UWP 中仍然不可用(请参阅相关问题)。

  2. 在 .NET Framework 中,它位于System.dllHttpUtility.

  3. 正确地转义了 URLs 的字符,不像Uri.EscapeUriString(参见drweb86's answer 的评论)。

  4. 它对字符串的长度没有任何限制,不像Uri.EscapeDataString(参见相关问题),因此它可以用于例如 POST 请求。

于 2013-06-03T10:07:25.337 回答
97

Levi Botelho 评论说,之前生成的编码表对于 .NET 4.5 不再准确,因为 .NET 4.0 和 4.5 之间的编码略有变化。所以我为 .NET 4.5 重新生成了表:

Unencoded UrlEncoded UrlEncodedUnicode UrlPathEncoded WebUtilityUrlEncoded EscapedDataString EscapedUriString HtmlEncoded HtmlAttributeEncoded WebUtilityHtmlEncoded HexEscaped
A         A          A                 A              A                    A                 A                A           A                    A                     %41
B         B          B                 B              B                    B                 B                B           B                    B                     %42

a         a          a                 a              a                    a                 a                a           a                    a                     %61
b         b          b                 b              b                    b                 b                b           b                    b                     %62

0         0          0                 0              0                    0                 0                0           0                    0                     %30
1         1          1                 1              1                    1                 1                1           1                    1                     %31

[space]   +          +                 %20            +                    %20               %20              [space]     [space]              [space]               %20
!         !          !                 !              !                    %21               !                !           !                    !                     %21
"         %22        %22               "              %22                  %22               %22              &quot;      &quot;               &quot;                %22
#         %23        %23               #              %23                  %23               #                #           #                    #                     %23
$         %24        %24               $              %24                  %24               $                $           $                    $                     %24
%         %25        %25               %              %25                  %25               %25              %           %                    %                     %25
&         %26        %26               &              %26                  %26               &                &amp;       &amp;                &amp;                 %26
'         %27        %27               '              %27                  %27               '                &#39;       &#39;                &#39;                 %27
(         (          (                 (              (                    %28               (                (           (                    (                     %28
)         )          )                 )              )                    %29               )                )           )                    )                     %29
*         *          *                 *              *                    %2A               *                *           *                    *                     %2A
+         %2b        %2b               +              %2B                  %2B               +                +           +                    +                     %2B
,         %2c        %2c               ,              %2C                  %2C               ,                ,           ,                    ,                     %2C
-         -          -                 -              -                    -                 -                -           -                    -                     %2D
.         .          .                 .              .                    .                 .                .           .                    .                     %2E
/         %2f        %2f               /              %2F                  %2F               /                /           /                    /                     %2F
:         %3a        %3a               :              %3A                  %3A               :                :           :                    :                     %3A
;         %3b        %3b               ;              %3B                  %3B               ;                ;           ;                    ;                     %3B
<         %3c        %3c               <              %3C                  %3C               %3C              &lt;        &lt;                 &lt;                  %3C
=         %3d        %3d               =              %3D                  %3D               =                =           =                    =                     %3D
>         %3e        %3e               >              %3E                  %3E               %3E              &gt;        >                    &gt;                  %3E
?         %3f        %3f               ?              %3F                  %3F               ?                ?           ?                    ?                     %3F
@         %40        %40               @              %40                  %40               @                @           @                    @                     %40
[         %5b        %5b               [              %5B                  %5B               [                [           [                    [                     %5B
\         %5c        %5c               \              %5C                  %5C               %5C              \           \                    \                     %5C
]         %5d        %5d               ]              %5D                  %5D               ]                ]           ]                    ]                     %5D
^         %5e        %5e               ^              %5E                  %5E               %5E              ^           ^                    ^                     %5E
_         _          _                 _              _                    _                 _                _           _                    _                     %5F
`         %60        %60               `              %60                  %60               %60              `           `                    `                     %60
{         %7b        %7b               {              %7B                  %7B               %7B              {           {                    {                     %7B
|         %7c        %7c               |              %7C                  %7C               %7C              |           |                    |                     %7C
}         %7d        %7d               }              %7D                  %7D               %7D              }           }                    }                     %7D
~         %7e        %7e               ~              %7E                  ~                 ~                ~           ~                    ~                     %7E

Ā         %c4%80     %u0100            %c4%80         %C4%80               %C4%80            %C4%80           Ā           Ā                    Ā                     [OoR]
ā         %c4%81     %u0101            %c4%81         %C4%81               %C4%81            %C4%81           ā           ā                    ā                     [OoR]
Ē         %c4%92     %u0112            %c4%92         %C4%92               %C4%92            %C4%92           Ē           Ē                    Ē                     [OoR]
ē         %c4%93     %u0113            %c4%93         %C4%93               %C4%93            %C4%93           ē           ē                    ē                     [OoR]
Ī         %c4%aa     %u012a            %c4%aa         %C4%AA               %C4%AA            %C4%AA           Ī           Ī                    Ī                     [OoR]
ī         %c4%ab     %u012b            %c4%ab         %C4%AB               %C4%AB            %C4%AB           ī           ī                    ī                     [OoR]
Ō         %c5%8c     %u014c            %c5%8c         %C5%8C               %C5%8C            %C5%8C           Ō           Ō                    Ō                     [OoR]
ō         %c5%8d     %u014d            %c5%8d         %C5%8D               %C5%8D            %C5%8D           ō           ō                    ō                     [OoR]
Ū         %c5%aa     %u016a            %c5%aa         %C5%AA               %C5%AA            %C5%AA           Ū           Ū                    Ū                     [OoR]
ū         %c5%ab     %u016b            %c5%ab         %C5%AB               %C5%AB            %C5%AB           ū           ū                    ū                     [OoR]

这些列表示编码如下:

  • 网址编码:HttpUtility.UrlEncode
  • UrlEncodedUnicode:HttpUtility.UrlEncodeUnicode
  • UrlPath 编码:HttpUtility.UrlPathEncode
  • WebUtilityUrl 编码:WebUtility.UrlEncode
  • 转义数据字符串:Uri.EscapeDataString
  • 转义UriString:Uri.EscapeUriString
  • Html 编码:HttpUtility.HtmlEncode
  • HtmlAttributeEncoded:HttpUtility.HtmlAttributeEncode
  • WebUtilityHtml 编码:WebUtility.HtmlEncode
  • 十六进制转义:Uri.HexEscape

笔记:

  1. HexEscape 只能处理前 255 个字符。因此,它会为拉丁 A 扩展字符(例如 Ā)抛出 ArgumentOutOfRange 异常。

  2. 此表是在 .NET 4.5 中生成的(有关 .NET 4.0 及以下版本的编码,请参阅答案https://stackoverflow.com/a/11236038/216440 )。

编辑:

  1. 由于 Discord 的回答,我添加了新的 WebUtility UrlEncode 和 HtmlEncode 方法,它们是在 .NET 4.5 中引入的。
于 2014-02-14T05:00:58.290 回答
69

.NET 中的 URL 编码很容易。采用:

System.Web.HttpUtility.UrlEncode(string url)

如果将对其进行解码以获取文件夹名称,您仍然需要排除文件夹名称中不能使用的字符(*、?、/ 等)

于 2009-02-22T18:57:46.060 回答
12

如果看不到 System.Web,请更改项目设置。目标框架应该是“.NET Framework 4”而不是“.NET Framework 4 Client Profile”

于 2011-03-20T05:20:04.230 回答
9

.NET 的实现UrlEncode不符合 RFC 3986。

  1. 有些字符没有编码,但应该编码。这些!()*字符在 RFC 的 2.2 节中列为必须编码的保留字符,但 .NET 无法对这些字符进行编码。

  2. 一些字符被编码但不应该被编码。这些.-_字符未在 RFC 的第 2.2 节中列为不应编码的保留字符。NET 错误地对这些字符进行编码。

  3. RFC 指定为保持一致,实现应使用大写 HEXDIG,而 .NET 生成小写 HEXDIG。

于 2013-05-21T22:21:31.740 回答
6

我认为这里的人们被 UrlEncode 消息转移了注意力。URLEncoding不是你想要的——你想要对在目标系统上不能作为文件名工作的东西进行编码。

假设您想要一些通用性——随意在多个系统(MacOS、Windows、Linux 和 Unix)上找到非法字符,将它们联合起来形成一组字符以进行转义。

至于转义,HexEscape 应该没问题(用 %XX 替换字符)。如果您想支持不执行 unicode 的系统,请将每个字符转换为 UTF-8 字节并对 >128 的所有内容进行编码。但是还有其他方法,例如使用反斜杠“\”或 HTML 编码“””。您可以创建自己的。任何系统所要做的就是“编码”掉不兼容的字符。上述系统允许您重新创建原始名称——但也可以用空格替换坏字符。

在与上述相同的切线上,唯一使用的是

Uri.EscapeDataString

-- 它对 OAuth 所需的所有内容进行编码,它不对 OAuth 禁止编码的内容进行编码,并将空格编码为 %20 而不是 +(也在 OATH 规范中)参见:RFC 3986。AFAIK,这是最新的 URI 规范。

于 2019-01-29T21:58:20.973 回答
4

我编写了一个对所有符号进行 url 编码的 C# 方法:

    /// <summary>
    /// !#$345Hf} → %21%23%24%33%34%35%48%66%7D
    /// </summary>
    public static string UrlEncodeExtended( string value )
    {
        char[] chars = value.ToCharArray();
        StringBuilder encodedValue = new StringBuilder();
        foreach (char c in chars)
        {
            encodedValue.Append( "%" + ( (int)c ).ToString( "X2" ) );
        }
        return encodedValue.ToString();
    }
于 2017-11-02T12:25:57.900 回答
1

理想情况下,这些将放在一个名为“FileNaming”的类中,或者只是将 Encode 重命名为“FileNameEncode”。注意:这些不是为处理完整路径而设计的,只是文件夹和/或文件名。理想情况下,您首先会拆分(“/”)您的完整路径,然后检查各个部分。显然,您可以将“%”字符添加到 Windows 中不允许的字符列表中,而不是联合,但我认为这种方式更有帮助/可读性/事实性。Decode() 完全相同,但将 Replace(Uri.HexEscape(s[0]), s) 与字符“转义”。

public static List<string> urlEncodedCharacters = new List<string>
{
  "/", "\\", "<", ">", ":", "\"", "|", "?", "%" //and others, but not *
};
//Since this is a superset of urlEncodedCharacters, we won't be able to only use UrlEncode() - instead we'll use HexEncode
public static List<string> specialCharactersNotAllowedInWindows = new List<string>
{
  "/", "\\", "<", ">", ":", "\"", "|", "?", "*" //windows dissallowed character set
};

    public static string Encode(string fileName)
    {
        //CheckForFullPath(fileName); // optional: make sure it's not a path?
        List<string> charactersToChange = new List<string>(specialCharactersNotAllowedInWindows);
        charactersToChange.AddRange(urlEncodedCharacters.
            Where(x => !urlEncodedCharacters.Union(specialCharactersNotAllowedInWindows).Contains(x)));   // add any non duplicates (%)

        charactersToChange.ForEach(s => fileName = fileName.Replace(s, Uri.HexEscape(s[0])));   // "?" => "%3f"

        return fileName;
    }

感谢@simon-tewsi 提供了上面非常有用的表格!

于 2013-02-08T22:05:18.197 回答
0

除了@Dan Herbert 的回答,我们通常应该只对值进行编码。

Split 有 params 参数 Split('&','='); 表达式首先由 & 然后 '=' 分割,所以奇数元素都是要编码的值,如下所示。

public static void EncodeQueryString(ref string queryString)
{
    var array=queryString.Split('&','=');
    for (int i = 0; i < array.Length; i++) {
        string part=array[i];
        if(i%2==1)
        {               
            part=System.Web.HttpUtility.UrlEncode(array[i]);
            queryString=queryString.Replace(array[i],part);
        }
    }
}
于 2013-03-01T08:07:20.217 回答