In this lesson, you will learn how to proactively defend your Razor views against Cross-Site Scripting (XSS) attacks by leveraging the engine's built-in output encoding.
Understanding the Threat
Cross-Site Scripting (XSS) occurs when an attacker injects malicious scripts into your web page that execute within the browsers of your unsuspecting users. In a Razor context, this usually happens if you take user-provided data and render it directly into your HTML without sanitization. If an attacker submits <script>alert('Hacked!');</script> as a username, a naive view implementation would render that script tag, and the browser would dutifully execute it.
Automatic Encoding in Razor
The good news is that the Razor engine is "secure by default." When you use the @ character to output dynamic data, Razor automatically performs HTML encoding. It converts dangerous characters like < and > into their safe, escaped HTML entities (< and >).
Consider this block:
<!-- Malicious input: <script>fetch('/steal-cookies')</script> -->
<p>Welcome back, @Model.UserName</p>
When rendered, Razor transforms the output into:
Welcome back, <script>fetch('/steal-cookies')</script>
Because the browser sees these as literal text rather than HTML tags, the script is rendered as harmless text on the page rather than being executed as code.
The Danger of "Raw" Output
You should exercise extreme caution if you ever encounter Html.Raw(). This method explicitly tells Razor to skip the encoding process and render the string exactly as it is provided.
<!-- DANGEROUS: Do not use with user-supplied content -->
<div>@Html.Raw(Model.UserBio)</div>
Only use Html.Raw() if the content is coming from a trusted internal source, such as a CMS that stores pre-sanitized HTML. If you must display user-submitted content that contains formatting (like a rich text editor), you must pass that data through a library that strips out dangerous tags—like <script> or onerror attributes—before it reaches the view, rather than relying on Html.Raw() to handle it.
Key Takeaway: Razor protects you automatically by HTML-encoding dynamic content; avoid using Html.Raw() unless the data source is completely trusted and sanitized.