menu

秋梦无痕

一场秋雨无梦痕,春夜清风冻煞人。冬来冷水寒似铁,夏至京北蟑满城。

Avatar

关于URLPathEncode

发信人: sEELa (sEELa), 信区: DotNET
标 题: 关于urlpathencode
发信站: BBS 水木清华站

研究了一下.NET里面的urlpathencode,并且和asp里面的urlpathencode比较了一下,有如下几点区别

1、encode scheme不同 试着在asp和asp.net里面运行具有同样功能的函数却有不同结果:

asp:
server.urlpathencode("ftp://music:music@127.0.0.1/PUB/Music/1.ChinaMale/阿杜/坚持到底/阿杜-惩罚.mp3")

结果:
ftp://music:music@127.0.0.1/PUB/Music/1.ChinaMale/%B0%A2%B6%C5/%BC%E1%B3%D6%B5%BD%B5%D7/%B0%A2%B6%C5-%B3%CD%B7%A3.mp3

asp.net:
system.web.httputility.urlpathencode("ftp://music:music@127.0.0.1/PUB/Music/1.ChinaMale/阿杜/坚持到底/阿杜-惩罚.mp3")

结果:
ftp://music:music@127.0.0.1/PUB/Music/1.ChinaMale/%e9%98%bf%e6%9d%9c/%e5%9d%9a%e6%8c%81%e5%88%b0%e5%ba%95/%e9%98%bf%e6%9d%9c-%e6%83%a9%e7%bd%9a.mp3

记得system.web.httputility下面还有一个urlencode的函数,定义如下:
Public Shared Function UrlEncode(ByVal str As String, ByVal e As System.Text.Encoding) As String

可以看到有个参数e,在asp中默认的用gb2312,而在asp.net默认的是utf-8。其实urlpathencode在.NEt里面默认的也是用的utf-8和asp中不同,造成了差异,结果是有的人在用.net的时候地址中一有中文就出错,实际上解决方法有如下两种:

一、让客户端用utf-8来发送接收地址
二、自己写一个用gb2312来编码的urlpathencode (.Net 没有为urlpathencode提供不同编码),比如如下的一个函数

Public Shared Function URLPathEncode(ByVal Str As String) As String
Dim filterChar() As Char = {":", "/", "\", "?", "=", "@"}
Dim chr As Char
Dim e As System.Text.Encoding = System.Text.Encoding.GetEncoding("gb2312")

For Each chr In Str
Dim p As Integer = filterChar.IndexOf(filterChar, chr)

If p >= 0 And p < filterChar.Length Then
URLPathEncode &= filterChar(p)
Else
URLPathEncode &= System.Web.HttpUtility.UrlEncode(chr, e).Replace("+", "%20")
End If

Next
End Function

2、urlpathencode(" ")返回"+",而这在asp返回"%20"

评论已关闭