When sharing server-side configuration with client-side JavaScript in ASP.NET Core Razor Pages, using Html.Raw() to inline JSON into a script block creates an XSS vulnerability. A safer pattern uses a <script type="application/json"> tag with a non-executable MIME type, which the browser treats as inert data. The JSON is read via document.getElementById and JSON.parse(element.textContent). On the C# side, JsonSerializerOptions with JavaScriptEncoder.UnsafeRelaxedJsonEscaping produces clean JSON, while Razor's default encoding handles the rest safely. The post also covers when to prefer a dedicated /config endpoint over inline injection, and provides a checklist of dos and don'ts.
Table of contents
Why the naive approach is dangerousA simple and clean solution: <script type="application/json">What on the C# side?What about a <meta> tag or a separate endpoint?Checklist1K Impressions