=== How to fix it in Razor

The following code is vulnerable to cross-site scripting because auto-escaping of special HTML characters has been disabled.
The recommended way to fix this code is to move the HTML content to the template and to only inject the dynamic value. Therefore, it is not necessary to disable auto-escaping.

[cols="a"]
|===
| ==== Noncompliant Code Example
|
[source,csharp]
----
using Microsoft.AspNetCore.Mvc;

public class HelloController : Controller
{
    public IActionResult Hello(string name)
    {
        ViewData["Hello"] = "<h1>Hello"+ name +"</h1>";
        return View("Hello");
     }
}
----
|
[source,html]
----
@Html.Raw(ViewData["Hello"])
----
| ==== Compliant Solution
|
[source,csharp]
----
using Microsoft.AspNetCore.Mvc;

public class HelloController : Controller
{
    public IActionResult Hello(string name)
    {
        ViewData["Name"] = name;
        return View("Hello");
     }
}
----
|
[source,html]
----
<h1>@ViewData["Name"]</h1>
----
|===

=== How does this work?

Template engines are used by web applications to build HTML content. Template files contain static HTML as well as template language instructions. These instructions allow, for example, to insert dynamic values in the document as the template is rendered. Template engines can auto-escape HTML special characters of dynamic values in order to prevent XSS vulnerabilities.

In .NET applications relying on Razor, the auto-escaping feature is enabled by default. XSS vulnerabilities arise when an untrusted value is injected in the template and auto-escaping is disabled using `++@Html.Raw++` or `++Microsoft.AspNetCore.Html.HtmlString++` expressions. This is often the case when a piece of dynamic HTML is generated from the code and used in a template variable.

include::../../common/fix/data_encoding.adoc[]

Razor engine auto-escaping only takes care of HTML entity endcoding. It will not prevent XSS if a variable is injected in an unquoted attribute or direcly in a script block.

=== Pitfalls

include::../../common/pitfalls/validation.adoc[]
