ASP.NET中通過ashx處理程序接收查詢字符串參數,發現Request.QueryString["id"]返回null或空值。
.ashx?id= 1 // 等號後有空格
URL查詢字符串中參數值前的空格被視為值的一部分,導致:
// 錯誤
window.location.href = "handler.ashx?id=" + userId + " "; // 多餘空格
// 正確
window.location.href = "handler.ashx?id=" + userId.trim();
string id = context.Request.QueryString["id"]?.Trim(); // 去除首尾空格
if (!string.IsNullOrEmpty(id)) {
// 業務邏輯
}
| 場景 | 編碼方法 | 示例 |
|---|---|---|
| JS構建URL | encodeURIComponent() | encodeURIComponent("值 1") → "值%201" |
| 後台生成URL | HttpUtility.UrlEncode() | UrlEncode("值 1") → "值+1" |
| 後台解析 | HttpUtility.UrlDecode() | 自動處理+/%20 |
// 輸出原始URL與解析結果對比
context.Response.Write("RawUrl: " + context.Request.RawUrl);
context.Response.Write("QueryString[id]: '" + context.Request.QueryString["id"] + "'");