Do you know how to render HTML strings?

Last updated by Charles Vionnet [SSW] 10 months ago.See history

Cross-site scripting (XSS) attacks occur when untrusted data is rendered on the browser without proper sanitization, thus potentially exposing the system to malicious scripts. To prevent XSS attacks, HTML encoding is typically applied to prevent the browser from interpreting HTML strings as code.

However, this approach can cause confusion when an application needs to output content that is already HTML encoded.

To solve this problem, the IHtmlString interface in .NET Core can be used to represent HTML content that is pre-encoded and should not be encoded again. This is to prevent double encoding, which can distort the original HTML content and cause it to display incorrectly on a web page.

string message = "Hello, <b>world</b>!";

Output: Hello, &lt;b&gt;world&lt;/b&gt;!

Figure: Bad example - A string containing HTML tags will be encoded

IHtmlContent message = new HtmlString("Hello, <b>world</b>!");

Output: Hello, <b>world</b>!

Figure: Good example - HTML tags using IHtmlContent will be treated as safe HTML and not encoded

You should only use IHtmlString when you are sure that the string doesn't contain any potentially harmful script tags. When dealing with user-provided content or content from an untrusted source, always sanitize or validate the HTML before rendering it.

We open source. Powered by GitHub