24

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 Answers 5

25

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

0
14

An alternative without a dependency to System.Web:

System.Net.WebUtility.HtmlEncode()
1
  • 1
    This encodes characters as HTML entities, e.g. "&" becomes "&amp;"
    – Skyfish
    Oct 16, 2020 at 13:33
9
using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);
3

You can use the HttpUtility.HtmlEncode method:

var htmlString = HttpUtility.HtmlEncode(user.Company);
1

HtmlUtility.HtmlEncode(string s)

1
  • It's a method called HtmlEncode in the HtmlUtility class which takes a string parameter and encodes it into a Html-safe string. That's a 23-word description which doesn't add any information to my answer, which is why I didn't include it in the first place
    – Rik
    May 21, 2014 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.