DevToolsForYou

HTML Escape Tool in C# / .NET — Code Examples

HTML Escape Tool in C# / .NETUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.

C# provides WebUtility.HtmlEncode in System.Net (all .NET targets) and HttpUtility.HtmlEncode in System.Web (ASP.NET only).

C# / .NET
using System;
using System.Net;

string raw = "<script>alert(\"xss\")</script> & \"quotes\"";

// Escape (System.Net.WebUtility — available in all .NET targets)
string escaped = WebUtility.HtmlEncode(raw);
Console.WriteLine(escaped);
// &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

// Unescape
string unescaped = WebUtility.HtmlDecode(escaped);
Console.WriteLine(unescaped);
// <script>alert("xss")</script> & "quotes"

// ASP.NET Core — use HtmlEncoder from Microsoft.Extensions.WebEncoders
// using System.Text.Encodings.Web;
// string encoded = HtmlEncoder.Default.Encode(raw);

// In Razor views, @variable is automatically HTML-encoded.
// Use @Html.Raw(variable) only for trusted, pre-escaped content.
Notes & gotchas
  • WebUtility.HtmlEncode is the preferred choice for non-ASP.NET code — it requires no extra packages.
  • In ASP.NET Core Razor, all @ expressions are auto-encoded; only @Html.Raw bypasses encoding.
  • HtmlEncoder.Default from Microsoft.Extensions.WebEncoders is more configurable and suitable for ASP.NET Core middleware.
Try it in your browser

Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open HTML Escape/Unescape
HTML Escape Tool in other languages