C# Interview Question #185

What is Cross-Site Scripting (XSS), and how is it prevented in ASP.NET Core?

Testing, Security, APIs & Reliability Senior Advanced

Quick Interview Answer

XSS occurs when untrusted content is rendered into a page in a way that allows attacker-controlled script or markup to execute in another user's browser.

Detailed Explanation

XSS occurs when untrusted content is rendered into a page in a way that allows attacker-controlled script or markup to execute in another user's browser.

Razor automatically HTML-encodes normal output, which provides an important default protection. Developers should avoid rendering untrusted input through Html.Raw.

When an application intentionally accepts HTML, it should be sanitized using an appropriate allow-list-based HTML sanitizer. Content Security Policy can provide an additional defense layer but does not replace correct output encoding.

Code Example

@Model.Comment

// Razor encodes normal output.
// Avoid this for untrusted content:
// @Html.Raw(Model.Comment)