在處理使用者輸入或資料庫欄位顯示於網頁時,需將特殊字元轉換為 HTML 實體編碼以防止 XSS 與排版錯誤。本文提供一組簡單易用的 HtmlEncode/HtmlDecode 靜態方法。
/// <summary>
/// 將字串中的特殊字元轉為 HTML 實體編碼
/// </summary>
public static string HtmlEncode(string input)
{
if (string.IsNullOrEmpty(input)) return input;
return input
.Replace("&", "&") // 必須最先處理 &
.Replace(">", ">")
.Replace("<", "<")
.Replace(" ", " ")
.Replace("\"", """)
.Replace("'", "'")
.Replace("\n", "
");
}
/// <summary>
/// 將 HTML 實體編碼還原為原始字元
/// </summary>
public static string HtmlDecode(string input)
{
if (string.IsNullOrEmpty(input)) return input;
return input
.Replace(">", ">")
.Replace("<", "<")
.Replace(" ", " ")
.Replace(""", "\"")
.Replace("'", "'")
.Replace("
", "\n")
.Replace("&", "&"); // 最後處理 &
}
string raw = @"";
string encoded = HtmlHelper.HtmlEncode(raw);
// 輸出:<script>alert('XSS')</script>
string decoded = HtmlHelper.HtmlDecode(encoded);
// 還原原始字串
&,解碼時最後處理,否則會重複轉換。System.Web.HttpUtility.HtmlEncode/Decode 或 System.Net.WebUtility.HtmlEncode/Decode (.NET Core/5+),支援完整實體表與效能優化。<br/>,可移除對 \n 的替換,改用 CSS white-space: pre-wrap。