I have an asp.net backend application and i am using web.config and other files to store configuration keys.
I have a front-end built with javascript files using knockout.js.
We would like to know how can we retrieve key value from web.config in backend and read this value in front-end using javascript and knockout.js.
Is there a simple way to do this ???, Views are javascript files and not asp.net web pages
<script>in your view/HTML/page files.Stringvalues when rendering them as JavaScript string literals! ...otherwise backslashes and quotes will be rendered literally which will break your rendered<script>element and likely introduce significant XSS vulnerabilities.In ASP.NET 4.x, use
HttpUtility.JavaScriptStringEncodeto ensure C#/.NETstringvalues are correctly and safely encoded to JavaScript strings.In ASP.NET Core you can continue to use
HttpUtility.JavaScriptStringEncode(in the now almost emptySystem.Web.dllSystem.Web.HttpUtility.dllin .NET Core 2.x or later) however now the preferred API in .NET isSystem.Text.Encodings.Web.JavaScriptEncoder'sEncodemethod (tip: useJavaScriptEncoder.Default.Encode).Note that
HttpUtility.JavaScriptStringEncodecan optionally add delimiting quotes for you, butSystem.Text.Encodings.Web.JavaScriptEncodernever renders outer quotes.For Razor
.cshtmlin ASP.NET MVC and ASP.NET 4.x WebPages:(I assume your
<head>is in_Layout.cshtml)For ASP.NET WebForms
.aspx/.ascx/.masterand/or ASP.NET MVC 1.x and 2.x using the WebForms ASPX View Engine:<head>is inLayout.master)<%=instead of<%:to render directly, btw, as we don't want to HTML-encode this JavaScript string literal.For ASP.NET Core MVC's Razor
.cshtmlviews:@inject IConfigurationto get immediate access to .NET Core's appSettings.HttpUtility.JavaScriptStringEncode(...)orSystem.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(...)in ASP.NET Core (including .NET 6).Html.Raw()to render the JS literal string. Do not use the normal Razor "write" syntax (i.e.@( value )or@value) because it will HTML-encode your JavaScript, which you don't want.Note that if you want
nullvalues from your appSettings.json to appear as JavaScriptnullliterals then you need to do that manually - you can use a@functionsmethod to handle this, like so:So now the
<script>above will be rendered as either this:...or this:
Any script (except ES Modules, I think?) can access
myAppSettingvia the implicitglobal(akawindow) object, as all top-levelvardeclarations become global properties.So like so: