在最近的一个项目中,我有幸排除了一个错误,该错误涉及当文件名中有空格时图片无法加载.我想“这是一个简单的问题,我会UrlEncode()吧!”但是,NAY!仅使用UrlEncode()无法解决问题.
@H_403_2@新问题是HttpUtilities.UrlEncode()方法将空格()转换为plusses()而不是像浏览器想要的那样.因此,文件图像name.jpg被正确找到时,文件图像name.jpg将返回not-found.
@H_403_2@值得庆幸的是,一位同事向我指出了HttpUtilities.UrlPathEncode(),它用于代替空格.
@H_403_2@为什么有两种处理Url编码的方法?为什么有两个命令行为如此不同?
解决方法
UrlEncode对于与QueryString一起使用很有用,因为当使用GET方法提交表单时,浏览器倾向于使用此处代替空格.
@H_403_2@UrlPathEncode只是替换了URL中无法使用的所有字符,例如<,>和.
@H_403_2@两条MSDN链接都包含此引用:
@H_403_2@You can encode a URL using with the UrlEncode method or the UrlPathEncode method. However,the methods return different results. The UrlEncode method converts each space character to a plus character (+). The UrlPathEncode method converts each space character into the string “%20”,which represents a space in hexadecimal notation. Use the UrlPathEncode method when you encode the path portion of a URL in order to guarantee a consistent decoded URL,regardless of which platform or browser performs the decoding.