UrlEncode & UrlDecode in ASP.NET

UrlEncode & UrlDecode in ASP.NET

前陣子還看到蠻常有人在問這二個問題的,結果發現自己習慣用的和別人不太一樣:我比較常用Server.UrlEncode,不過有些人習慣的是HttpUtility.UrlEncode;這二個差別可以從程式碼看得出來…

HttpServerUtility的預設編碼模式是從Response截取,而HttpUtility則是預設UTF8,我們通常都用UTF8編碼,所以沒什麼差;如果不是利用UTF8編碼的時候,使用上就要小心一點。


//Server.UrlEncode
public sealed class HttpServerUtility
{

	public string UrlEncode(string s)
	{
		Encoding e = (this._context != null) ? this._context.Response.ContentEncoding : Encoding.UTF8;
		return HttpUtility.UrlEncode(s, e);
	}

	public string UrlDecode(string s)
	{
		Encoding e = (this._context != null) ? this._context.Request.ContentEncoding : Encoding.UTF8;
		return HttpUtility.UrlDecode(s, e);
	}

}

//HttpUtility.UrlEncode
public sealed class HttpUtility
{
	public static string UrlEncode(string str)
	{
		if (str == null)
		{
			return null;
		}
		return UrlEncode(str, Encoding.UTF8);
	}
	
	public static string UrlDecode(string str)
	{
		if (str == null)
		{
			return null;
		}
		return UrlDecode(str, Encoding.UTF8);
	}
 
}

 

DotBlogs 的標籤: