在ASP.NET中,为什么有UrlEncode()和UrlPathEncode()?
在最近的一个项目中,我很高兴解决了一个错误,该错误涉及当文件名中包含空格时图像无法加载。我想“多么简单的问题,我会UrlEncode()
它!”但是,不!仅使用 UrlEncode()
并不能解决问题。
新问题是 HttpUtilities.UrlEncode()
方法将空格 () 切换为加号 (
+
) 而不是 %20
就像浏览器想要的那样。因此,file+image+name.jpg
将返回 not-found,而 file%20image%20name.jpg
已正确找到。
值得庆幸的是,一位同事向我指出 HttpUtilities.UrlPathEncode()
使用 %20
表示空格,而不是 +
。
为什么有两种处理 Url 编码的方法?为什么有两个命令的行为如此不同?
In a recent project, I had the pleasure of troubleshooting a bug that involved images not loading when spaces were in the filename. I thought "What a simple issue, I'll UrlEncode()
it!" But, NAY! Simply using UrlEncode()
didn't resolve the problem.
The new problem was the HttpUtilities.UrlEncode()
method switched spaces () to plusses (
+
) instead of %20
like the browser wanted. So file+image+name.jpg
would return not-found while file%20image%20name.jpg
was found correctly.
Thankfully, a coworker pointed out HttpUtilities.UrlPathEncode()
to me which uses %20
for spaces instead of +
.
WHY are there two ways of handling Url encoding? WHY are there two commands that behave so differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
UrlEncode 对于与 QueryString 一起使用非常有用,因为浏览器倾向于使用 <使用
GET
方法提交表单时,此处的 code>+ 代替空格。UrlPathEncode 只是替换所有不能使用的字符在 URL 中,例如
<
、>
和。
两个 MSDN 链接都包含以下引用:
UrlEncode is useful for use with a QueryString as browsers tend to use a
+
here in place of a space when submitting forms with theGET
method.UrlPathEncode simply replaces all characters that cannot be used within a URL, such as
<
,>
and.
Both MSDN links include this quote:
所以在 URL 中你有路径,然后是 ?然后是参数(即 http://some_path/page.aspx?parameters)。 URL 路径对空格的编码与 url 参数的编码不同,这就是存在两个版本的原因。很长一段时间以来,空格在 URL 中无效,但在参数中有效。
换句话说,格式化 url 随着时间的推移而改变。长期以来,URL 中也只能使用 ANSI 字符。
So in a URL you have the path and then a ? and then the parameters (i.e. http://some_path/page.aspx?parameters). URL paths encode spaces differently then the url parameters, that's why there is the two versions. For a long time spaces were not valid in a URL, but were in in the parameters.
In other words the formatting urls has changed over time. For a long time only ANSI chars could be in a URL too.