Cross-site scripting (XSS) and output encoding
If a page prints user input as HTML, that input can run as script in other users’ browsers. Encoding output stops it.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
XSS happens when untrusted text is placed into a page in a way the browser treats as markup or script. Stored XSS saves it (a comment); reflected XSS bounces it from the URL. Context-aware output encoding turns special characters like < and > into harmless entities, so the browser shows them instead of running them.
Code
// Vulnerable: raw HTML from the user goes into the page
html += "<p>" + comment.Text + "</p>";
// Safe: encode for the HTML context before output
html += "<p>" + HtmlEncoder.Default.Encode(comment.Text) + "</p>";
// Razor encodes @comment.Text automatically
// Extra layers: Content-Security-Policy, HttpOnly cookiesTips
- Encode on output, for the right context (HTML body, attribute, JavaScript, URL).
- Frameworks like Razor, React and Angular encode by default; the danger is in raw-HTML escape hatches.
- Content-Security-Policy blocks inline and unexpected scripts as a second layer; HttpOnly cookies stop script from reading the session cookie.
- If users must post rich text, sanitise it with an allow-list HTML sanitizer.
In the .NET library
Razor views encode @expressions; Html.Raw turns that off, so treat every Html.Raw as a review flag.