你如何正确地逃避.NET中的文档名称?

Mik*_*sen 9 .net html c# escaping

我们在我们的Web服务器(人们上传它们)上存储了一堆奇怪的文档名称,这些文档名称包含空格,符号等各种字符.当我们生成这些文档的链接时,我们需要将它们转义,以便服务器可以通过以下方式查找文件:它在数据库中的原始名称.但是,在所有情况下,内置的.NET转义函数都不会正常工作.

拿文件Hello#There.docx:

UrlEncode 将正确处理:

HttpUtility.UrlEncode("Hello#There");
"Hello%23There"
Run Code Online (Sandbox Code Playgroud)

然而,UrlEncode处理Hello There.docx正确:

HttpUtility.UrlEncode("Hello There.docx");
"Hello+There.docx"
Run Code Online (Sandbox Code Playgroud)

+符号仅对URL参数有效,而不对文档名称有效.有趣的是,这实际上适用于Visual Studio测试Web服务器,但不适用于IIS.

UrlPathEncode函数适用于空格:

HttpUtility.UrlPathEncode("Hello There.docx");
"Hello%20There.docx"
Run Code Online (Sandbox Code Playgroud)

但是,它不会逃避其他角色,如#角色:

HttpUtility.UrlPathEncode("Hello#There.docx");
"Hello#There.docx"
Run Code Online (Sandbox Code Playgroud)

此链接无效,因为它#被解释为URL哈希,甚至从未到达服务器.

是否有.NET实用程序方法来转义文档名称中的所有非字母数字字符,或者我是否必须自己编写?

dtb*_*dtb 15

看看Uri.EscapeDataString方法:

Uri.EscapeDataString("Hello There.docx")  // "Hello%20There.docx"

Uri.EscapeDataString("Hello#There.docx")  // "Hello%23There.docx"
Run Code Online (Sandbox Code Playgroud)


Bro*_*ass 6

我会以不同的方式处理它:不要在查找中使用文档名称作为键 - 使用Guid或其他一些id参数,您可以映射到数据库中磁盘上的文档名称.这不仅保证了唯一性,而且你也不会首先遇到这种逃避问题.

  • 为什么不能在响应中使用`content-disposition` HTTP标头?这应该允许您设置文件名 (2认同)