【问题标题】:URL Encoding using C#使用 C# 进行 URL 编码
【发布时间】:2010-10-09 04:39:12
【问题描述】:

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

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

c:\tempfolder\date\用户名

问题是一些用户名抛出“非法字符”异常。例如,如果我的用户名是 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 值或任何其他可以轻松识别字符的值。

【问题讨论】:

标签: c# .net urlencode


【解决方案1】:

我一直在试验 .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]

列表示编码如下:

  • UrlEncoded:HttpUtility.UrlEncode

  • UrlEncodedUnicode:HttpUtility.UrlEncodeUnicode

  • UrlPathEncoded:HttpUtility.UrlPathEncode

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

  • 转义UriString:Uri.EscapeUriString

  • HtmlEncoded:HttpUtility.HtmlEncode

  • HtmlAttributeEncoded:HttpUtility.HtmlAttributeEncode

  • 十六进制转义:Uri.HexEscape

注意事项:

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

  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();
            }
        }
    }
}

Click here to run code on dotnetfiddle.net

【讨论】:

  • 这是一个绝妙的答案。原来我想使用 Uri.EscapeDataString 而不是 System.Web。感谢这张桌子。
  • 请注意,这不再是 100% 准确的。 .NET 4 和 .NET 4.5 之间的某些功能略有变化。见stackoverflow.com/q/20003106/1068266
  • @Levi:感谢您的提醒。我在 .NET 4.5 的表格中添加了第二个答案。我已经编辑了原始答案以链接到第二个表格。
  • 请注意,.NET 文档说 不要使用;仅用于浏览器兼容性。使用 UrlEncode。,但该方法会编码许多其他不需要的字符。最接近的是Uri.EscapeUriString,但要注意它不支持null 参数。
  • 我忘了说,我上面的评论是给UrlPathEncode的。所以基本上用Uri.EscapeUriString替换UrlPathEncode
【解决方案2】:

您应该只对用户名或 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 所述,您仍然需要确保删除非法文件名字符,否则文件系统将不喜欢该路径。

【讨论】:

  • 使用 HttpUtility.UrlPathEncode 方法应该可以防止您在此处描述的问题。
  • @DJ Pirtu:确实,UrlPathEncode 不会对路径进行那些不需要的更改,但是它也不会在 ? 之后对任何内容进行编码(因为它假定查询字符串已经编码)。在 Dan Herbert 的示例中,他似乎在假装 Example 是需要编码的文本,因此 HttpUtility.UrlPathEncode("http://www.google.com/search?q=Example"); 将不起作用。用?q=Ex&amp;ple 试试(期望的结果是?q=Ex%26ple)。它不会起作用,因为 (1) UrlPathEncode 在? 之后不会触及任何东西,并且 (2) UrlPathEncode 无论如何都不会对&amp; 进行编码。
  • 请看这里:connect.microsoft.com/VisualStudio/feedback/details/551839/… 我应该补充一点,UrlPathEncode 不编码&amp; 当然很好,因为您需要它来分隔查询字符串参数。但有时您也需要编码的 & 符号。
  • HttpUtility 在最新版本中被 WebUtility 继承,节省一些时间:)
【解决方案3】:

更好的方法是使用

Uri.EscapeUriString

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

【讨论】:

  • 完全同意,因为“客户端配置文件”对于使用 System.Net 但不使用 System.Web 的应用程序来说通常就足够了;-)
  • OP 正在讨论检查它的文件系统兼容性,所以这不起作用。 Windows 不允许的字符集是 '["/", "\\", "", ":", "\"", "|", "?", "*"]' 但其中很多不要使用 EscapedUriString 进行编码(请参见下表 - 感谢@Simon Tewsi 提供该表)...“在本地机器上创建路径”-OP UrlEncoded 几乎可以解决所有问题,但不能解决原始输入中存在“%”或“%3f”的问题,因为“解码”现在与原始输入不同。
  • 只是为了说清楚:这个答案对文件系统不起作用
  • 此外,从 .NET Framework 4.5 开始,客户端配置文件已停用,只有完整的可再发行包可用。
  • stackoverflow.com/a/34189188/3436164 使用 Uri.EscapeDataString 而不是 Uri.EscapeUriString 阅读此评论,它帮助了我。
【解决方案4】:

编辑:请注意,此答案现已过时。请参阅Siarhei Kuchuk's answer below 以获得更好的修复

UrlEncoding 将按照您在此处的建议进行操作。如前所述,使用 C#,您只需使用 HttpUtility

您也可以对非法字符进行正则表达式然后替换,但这要复杂得多,因为您必须有某种形式的状态机(例如 switch ... case)才能用正确的字符替换。因为UrlEncode 是预先做的,所以很容易。

对于 Linux 与 Windows,有一些字符在 Linux 中是可接受的,但在 Windows 中是不可接受的,但我不会担心,因为文件夹名称可以通过使用 UrlDecode 解码 Url 字符串来返回,这样您就可以往返更改。

【讨论】:

  • 这个答案现在已经过时了。阅读下面的一些答案 - 从 .net45 开始,这可能是正确的解决方案:msdn.microsoft.com/en-us/library/…
  • 对于 FTP,每个 Uri 部分(文件夹或文件名)可以使用 Uri.EscapeDataString(fileOrFolderName) 构建,允许所有非 Uri 兼容字符(空格、unicode ...)。例如,要允许文件名中包含任何字符,请使用: req =(FtpWebRequest)WebRequest.Create(new Uri(path + "/" + Uri.EscapeDataString(filename)));使用 HttpUtility.UrlEncode() 用加号 (+) 替换空格。搜索引擎的正确行为,但文件/文件夹名称不正确。
  • asp.net 会阻止 url 中的大多数 xss,因为当您尝试添加 js 脚本 A potentially dangerous Request.Path value was detected from the client 时会收到警告。
【解决方案5】:

.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 中仍然不可用(请参阅 @987654323 @)。

  2. 在 .NET Framework 中,它驻留在System.dll,因此它不需要任何额外的引用,这与HttpUtility 不同。

  3. 正确地转义 URL 的字符,不像 Uri.EscapeUriString(参见 comments to drweb86's answer)。

  4. 对字符串的长度没有任何限制,不像Uri.EscapeDataString(见related question),所以它可以用于例如POST请求。

【讨论】:

  • 我喜欢它使用“+”而不是 %20 作为空格进行编码的方式。但是这个仍然没有从 URL 中删除“并且给了我无效的 URL……哦,好吧……只是将不得不做一个替换(“”“”“,”)
【解决方案6】:

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
  • UrlPathEncoded:HttpUtility.UrlPathEncode
  • WebUtilityUrlEncoded:WebUtility.UrlEncode
  • 转义数据字符串:Uri.EscapeDataString
  • EscapedUriString: Uri.EscapeUriString
  • HtmlEncoded:HttpUtility.HtmlEncode
  • HtmlAttributeEncoded: HttpUtility.HtmlAttributeEncode
  • WebUtilityHtmlEncoded: WebUtility.HtmlEncode
  • 十六进制转义:Uri.HexEscape

注意事项:

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

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

编辑:

  1. 根据 Discord 的回答,我添加了 .NET 4.5 中引入的新 WebUtility UrlEncode 和 HtmlEncode 方法。

【讨论】:

  • No not user UrlPathEncode - 甚至 MSDN 都说不能使用它。它是为解决 netscape 2 msdn.microsoft.com/en-us/library/… 的问题而构建的
  • Server.URLEncode 是这个主题的另一个变体吗?它会产生任何不同的输出吗?
  • @ALEX:在 ASP.NET 中,Server 对象是 HttpServerUtility 的一个实例。使用 dotPeek 反编译器,我查看了 HttpServerUtility.UrlEncode。它只是调用 HttpUtility.UrlEncode 所以这两个方法的输出是相同的。
  • 看起来,即使有这么多的编码方法,对于拉丁 1 以上的任何东西,例如 → 或 ☠,它们都仍然非常失败。 (UrlEncodedUnicode 似乎至少尝试支持 Unicode,但已弃用/丢失。)
  • Simon,你能把这个答案整合到接受的答案中吗?将它放在一个答案中会很好。您可以整合它并在该答案的底部制作一个 h1 标题,或者整合到一个表格中,并标记不同的行,例如:(Net4.0) ? %3f................................(Net4.5) ? %3f ..................................
【解决方案7】:

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

System.Web.HttpUtility.UrlEncode(string url)

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

【讨论】:

  • 它是否对每个不属于字母表的字符进行编码?
  • URL 编码将 URL 中不允许的字符转换为字符实体等价物。不安全字符列表:blooberry.com/indexdot/html/topics/urlencoding.htm
  • HttpUtility.UrlEncode 上的 MSDN 链接:msdn.microsoft.com/en-us/library/4fkewx0t.aspx
  • 最好将完整的 System.Web... 部分放入您的答案中,这样可以为很多人节省一点时间 :) 谢谢
  • 这很危险:不是url的所有字符都必须编码,只有querystring的参数值。您建议的方式还将编码在查询字符串中创建多个参数所需的 & 。解决方案是根据需要对参数的每个值进行编码
【解决方案8】:

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

【讨论】:

  • 在我看来,开发人员应该了解“.NET 配置文件”,他们应该使用正确的来实现他们的目的!只是添加完整的配置文件以获取(例如 System.Web)而不知道他们为什么添加完整的配置文件,这不是很聪明。 客户端应用程序和完整配置文件仅在需要时使用“客户端配置文件”(例如,WinForms 或 WPF 客户端应使用客户端配置文件而不是完整配置文件)!例如我看不出在客户端应用程序中使用 HttpServerUtility 的原因^^ ...如果需要,那么应用程序的设计就有问题!
  • 真的吗?从来没有看到需要客户端应用程序来构建 URL?你以什么为生 - 做清洁工作?
  • @hfrmobile:没有。配置文件模型(它只存在一次并在下一个版本中被放弃)都是错误的。从一开始就很明显。现在对你来说很明显吗?首先想一想,不要接受 msft 试图卖给你的一切“原样”;P
  • 抱歉,我从未说过客户端永远不必构建/使用 URL。只要 .NET 4.0 还在使用中,用户就应该关心它。简而言之:开发人员在将 HttpServerUtility 添加到客户端之前应该三思而后行。还有其他/更好的方法,只需查看 139 票的答案或“从 .NET Framework 4.5 开始,您可以使用 WebUtility.UrlEncode。首先,它驻留在 System.dll 中,因此不需要任何额外的引用。”。跨度>
【解决方案9】:

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

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

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

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

【讨论】:

    【解决方案10】:

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

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

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

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

    Uri.EscapeDataString

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

    【讨论】:

      【解决方案11】:

      我编写了一个对所有符号进行 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();
          }
      

      【讨论】:

        【解决方案12】:

        理想情况下,这些将放在一个名为“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 提供了上面非常有用的表格!

        【讨论】:

        • 也很有用:Path.GetInvalidFileNameChars()
        • 是的。这是一种方法: foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { filename = filename.Replace(c, '_'); }
        【解决方案13】:

        除了@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);
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-03
          • 1970-01-01
          • 1970-01-01
          • 2014-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-02
          相关资源
          最近更新 更多