---
title: Output Encoding Before Interpreter Use
impact: HIGH
impactDescription: prevents XSS and injection attacks
tags: xss, encoding, output, html, security, csharp, razor
---

## Output Encoding Before Interpreter Use

XSS attacks occur when unescaped user data is rendered in the browser. In ASP.NET Core, Razor automatically encodes output, but using `Html.Raw` or unsafe rendering bypasses this.

**Incorrect (no encoding):**

```csharp
// Razor View - XSS Vulnerability
@Html.Raw(Model.UserDescription) 

// Returning raw HTML from Controller
return Content($"<h1>Hello {userInput}</h1>", "text/html");
```

**Correct (context-aware encoding):**

```csharp
// Razor - Auto-encoded (Safe)
@Model.UserDescription

// If you MUST use Html.Raw, sanitize first
@Html.Raw(_sanitizer.Sanitize(Model.UserDescription))

// Controller - Use libraries
using System.Text.Encodings.Web;
var safeHtml = HtmlEncoder.Default.Encode(userInput);
```

**Tools:** Roslyn Analyzers, SonarQube (S5131)
