以下代码在.NET Framework 2.0中测试。
先看一个例子:
// 将“A+B”编码后赋给变量parameters
string parameters = Server.UrlEncode( " A+B " );
// 此时,变量 parameters 的值为 "A%2bB"
// 将该参数传递给测试页面
Response.Redirect( " test.aspx?p= " + parameters);
test.aspx页面:
protected void Page_Load( object sender, EventArgs e)
{
if ( ! IsPostBack)
{
if (Request.QueryString[ " p " ] != null )
{
// 获取Url参数的值
string parameters = Request.QueryString[ " p " ].ToString();
// Url解码
parameters = Server.UrlDecode(parameters);
// 此时,参数 parameters 的值为???
Response.Write(parameters);
}
}
}
当参数 parameters 输出到页面后,值已经不为“A+B”了,而变成“A B”,将“+”变成了空格。
原因:
在test.aspx页面,“Request.QueryString”中的值仍然是“A%2bB”,但通过Request.QueryString["p"]取值时,得到的结果已经被自动解码了(注意)。
那么在“string parameters = Request.QueryString["p"].ToString();”条语句执行完后,parameters 的值已经为“A+B”了。
然后再执行“parameters = Server.UrlDecode(parameters);”条语句时,等于对“A+B”进行了解码。
解码后的值变成了“A B”(A空格B)。
疑问:
“A+B”解码后为什么变成"A B"(将“+”解码为空格)? 请高手赐教。
以下代码来源于.NET Framework 2.0,红色显示部分为造成该问题的原因。
// .NET Framework 2.0 中的代码
private static string UrlDecodeStringFromStringInternal( string s, Encoding e)
{
int length = s.Length;
UrlDecoder decoder = new UrlDecoder(length, e);
for ( int i = 0 ; i < length; i ++ )
{
char ch = s[i];
if (ch == ' + ' )
{
ch = ' ' ;
}
else if ((ch == ' % ' ) && (i < (length - 2 )))
{
if ((s[i + 1 ] == ' u ' ) && (i < (length - 5 )))
{
int num3 = HexToInt(s[i + 2 ]);
int num4 = HexToInt(s[i + 3 ]);
int num5 = HexToInt(s[i + 4 ]);
int num6 = HexToInt(s[i + 5 ]);
if (((num3 < 0 ) || (num4 < 0 )) || ((num5 < 0 ) || (num6 < 0 )))
{
goto Label_0106;
}
ch = ( char )((((num3 << 12 ) | (num4 << 8 )) | (num5 << 4 )) | num6);
i += 5 ;
decoder.AddChar(ch);
continue ;
}
int num7 = HexToInt(s[i + 1 ]);
int num8 = HexToInt(s[i + 2 ]);
if ((num7 >= 0 ) && (num8 >= 0 ))
{
byte b = ( byte )((num7 << 4 ) | num8);
i += 2 ;
decoder.AddByte(b);
continue ;
}
}
Label_0106:
if ((ch & 0xff80 ) == 0 )
{
decoder.AddByte(( byte )ch);
}
else
{
decoder.AddChar(ch);
}
}
return decoder.GetString();
}