How to convert string to HTML safe string

2019-03-25 08:17发布

I am creating a some dynamically generated HTML

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

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.

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.

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

HttpUtility.JavaScriptStringEncode(user.Company);

5条回答
聊天终结者
2楼-- · 2019-03-25 08:43
using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);
查看更多
干净又极端
3楼-- · 2019-03-25 08:44

An alternative without a dependency to System.Web:

System.Net.WebUtility.HtmlEncode()
查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-25 08:45

You can use the HttpUtility.HtmlEncode method:

var htmlString = HttpUtility.HtmlEncode(user.Company);
查看更多
We Are One
6楼-- · 2019-03-25 08:58

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));

There is also the inverse way using HttpUtility.HtmlDecode(string).

查看更多
登录 后发表回答