如何将字符串转换为HTML安全字符串

如何将字符串转换为HTML安全字符串

问题描述:

我正在创建一些动态生成的HTML

I am creating a some dynamically generated HTML

bldr.AppendLine("<a>");
string userText = user.Company;
bldr.AppendLine(userText);
bldr.AppendLine("</a>");

如何确保公司名称是什么,会按原样出现,但如果他们尝试使用这个名字注入任何HTML,它只会以纯文本形式出现。

How can I ensure that whatever the company's name is, will appear as it should, but also if they try to inject any HTML in thier name it will simply appear in plain text.

例如,如果他们尝试使用名称< script&gt ; alert(Do Bad!)< / script> 这就是纯文本中出现的页面。

For instance if they tried to use the name "<script>alert("Do Bad!")</script>" that's exactly what will appear on the page, in plain text.

但我也想避免A& C翻译成A \0026C,这是当我使用

But I also want to avoid "A & C" translating to "A \u0026 C", which is what happens when I use

HttpUtility.JavaScriptStringEncode(user.Company);


您可以使用相同的类 HttpUtility 您可以使用javascript,但对于 html ,可以使用示例:

You can use the same class HttpUtility you have use to javascript, but, for html, for sample:

bldr.AppendFormat("<a>{0}</a>\n", HttpUtility.HtmlEncode(user.Company));

还有使用 HttpUtility.HtmlDecode(string)