如何将字符串转换为HTML安全字符串 [英] How to convert string to HTML safe string

查看:207
本文介绍了如何将字符串转换为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> ; 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)

这篇关于如何将字符串转换为HTML安全字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆