js中escape对应的C#解码函数 System.Web.HttpUtility.UrlDecode(s) //注意编码
----------------------------------------------------------------------------------------------
需要注意的几点:
1、HttpUtility.UrlEncode,HttpUtility.UrlDecode是静态方法,而Server.UrlEncode,Server.UrlDecode是实例方法。
2、Server是HttpServerUtility类的实例,是System.Web.UI.Page的属性。
3、用HttpUtility.UrlEncode编码后的字符串和用Server.UrlEncode进行编码后的字符串对象不一样:
例如:
string url="http://search.99read.com/index.aspx?book_search=all&main_str=奥迷尔";
Response.Write(HttpUtility.UrlEncode(url));
Response.Write("<br>");
Response.Write(Server.UrlEncode(url));
输出结果是:
http%3a%2f%2fsearch.99read.com%2findex.aspx%3fbook_search%3dall%26main_str%3d%e5%a5%a5%e8%bf%b7%e5%b0%94
http%3a%2f%2fsearch.99read.com%2findex.aspx%3fbook_search%3dall%26main_str%3d%b0%c2%c3%d4%b6%fb
原因:Server.UrlEncode的编码方式是按照本地程序设置的编码方式进行编码的,而HttpUtility.UrlEncode是默认的按照.net的utf-8格式进行编码的。
如果改一下程序:
string url1="http://search.99read.com/index.aspx?book_search=all&main_str=奥迷尔";
Response.Write(HttpUtility.UrlEncode(url1,System.Text.Encoding.GetEncoding("GB2312")));
Response.Write("<br>");
Response.Write(Server.UrlEncode(url1));
输出的结果是:
http%3a%2f%2fsearch.99read.com%2findex.aspx%3fbook_search%3dall%26main_str%3d%b0%c2%c3%d4%b6%fb
http%3a%2f%2fsearch.99read.com%2findex.aspx%3fbook_search%3dall%26main_str%3d%b0%c2%c3%d4%b6%fb
3、有时候可能别的系统传递过来的url是用别的编码方式编码的。
介绍自己编写的一个方法,可以获取指定编码格式的QueryString。
public string GetNonNullQueryString(string key,Encoding encoding)
{
//引用System.Collections.Specialized和System.Text命名空间
string stringValue;
System.Collections.Specialized.NameValueCollection encodingQueryString;
//该方法是在2.0中新增的
encodingQueryString = HttpUtility.ParseQueryString(Request.Url.Query,encoding);
//'里面的key就是你提交的参数的Key
return encodingQueryString[key] != null ? encodingQueryString[key].Trim() : "";
}
调用:
string url = GetNonNullQueryString("url",Encoding.UTF8).Trim();