2009-09-17 58 views
0

C#,ASP.NET 3.5請求對象不解碼了urlencoded

創建簡單的URL與編碼查詢字符串:

string url = "http://localhost/test.aspx?a=" + 
    Microsoft.JScript.GlobalObject.escape("áíóú"); 

成爲很好:http://localhost/test.aspx?a=%E1%ED%F3%FA(即良好)

當我調試test.aspx我得到奇怪的解碼:

string badDecode = Request.QueryString["a"]; //bad 
string goodDecode = Request.Url.ToString(); //good 

爲什麼會曲eryString不解碼值?

+0

會發生什麼事,當你做字符串badDecode =的Request.QueryString [ 「一個」]。的ToString();? ToString()是語言環境特定的線程,有時可以做魔術。 – 2009-09-17 23:28:42

回答

1

你可以嘗試使用HttpServerUtility.UrlEncode代替。在Microsoft.JScript.GlobalObject.escape狀態,它不是inteded

微軟文檔,直接從您的代碼中使用。

編輯:
正如我在評論中說:這兩種方法不同的編碼和預計的Request.QueryString通過HttpServerUtility.UrlEncode使用的編碼,因爲它內部使用HttpUtility.UrlDecode。

(HttpServerUtility.UrlEncode實際使用HttpUtility.UrlEncode內部。)

你可以很容易地看到這兩種方法之間的差異。
創建一個新的ASP.NET Web應用程序,添加到Microsoft.JScript程序的引用,然後添加以下代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    var msEncode = Microsoft.JScript.GlobalObject.escape("áíóú"); 
    var httpEncode = Server.UrlEncode("áíóú"); 

    if (Request.QueryString["a"] == null) 
    { 
    var url = "/default.aspx?a=" + msEncode + "&b=" + httpEncode; 
    Response.Redirect(url); 
    } 
    else 
    { 
    Response.Write(msEncode + "<br />"); 
    Response.Write(httpEncode + "<br /><br />"); 

    Response.Write(Request.QueryString["a"] + "<br />"); 
    Response.Write(Request.QueryString["b"]); 
    } 
} 

結果應該是:

%E1%ED%F3%FA 
%c3%a1%c3%ad%c3%b3%c3%ba 

���� 
áíóú 
+0

問題不在於編碼器,這是因爲接收頁面中的QueryString部分亂碼。 – 2009-09-17 19:24:53

+0

我嘗試了Microsoft.JScript.GlobalObject.escape和HttpServerUtility.UrlEncode,前者給出亂碼,後者工作正常。 – 2009-09-18 05:34:56

+0

這些方法編碼不同。 QueryString需要HttpServerUtility.UrlEncode使用的格式。 – 2009-09-18 05:44:19