ASP.NET 提供 System.Web.HttpUtility.HtmlEncode 與 UrlEncode 靜態方法,分別用於將字串安全輸出至 HTML 內容與 URL 參數,防止 XSS 與參數截斷。
| 原始字串 | HtmlEncode 結果 | UrlEncode 結果 |
|---|---|---|
| <h1>Test & Demo</h1> | <h1>Test & Demo</h1> | %3ch1%3eTest+%26+Demo%3c%2fh1%3e |
| url?a=1&b=2 | url?a=1&b=2 | url%3fa%3d1%26b%3d2 |
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.HttpUtility" %>
<script runat="server">
void Page_Load()
{
string html = "<h1>Hello & World</h1>";
string url = "page.aspx?id=1&name=test";
lblHtml.Text = html;
lblHtmlEncoded.Text = HtmlEncode(html);
lblUrl.Text = url;
lblUrlEncoded.Text = UrlEncode(url);
}
</script>
<html><body>
原始 HTML: <asp:Label id="lblHtml" runat="server" /><br>
HtmlEncode: <asp:Label id="lblHtmlEncoded" ForeColor="Blue" runat="server" /><br>
原始 URL: <asp:Label id="lblUrl" runat="server" /><br>
UrlEncode: <asp:Label id="lblUrlEncoded" ForeColor="Blue" runat="server" />
</body></html>
HtmlEncode(或 HtmlAttributeEncode)UrlEncodeJavaScriptStringEncode (ASP.NET 4.5+)