I am trying to read apiUrl key value from web.config file so that I can take advantage of the .net transform config to manage deployment in different environments. Here is my Webconfig code:
<appSettings>
<add key="url" value="http://localhost:6299/api/"
</appSettings>
and in the plain js file I have this code:
var apiUrl = '<%=ConfigurationManager.AppSettings["url"].Tostring()
%>'.
It is not giving the url value. How can I read web.config value in javascript file?
"In the plain js file"
do you mean a file ending in .js ?
.js files are not parsed server-side so the <%= values are not converted. This works for the other answer ("worked for me") as they will have it in the .aspx/.cshtml file rather than a 'plain .js file'.
You'll need to move your code to your .aspx/.cshtml or you'll need to pass the url value in to your js (eg) via a function parameter from the .aspx/.cshtml file.
Below code worked for me.
<script>
var apiUrl = '@System.Configuration.ConfigurationManager.AppSettings["url"]';
</script>
Below code worked for me in ASP.Net webforms application, but not in MVC application
var key = '<%= System.Configuration.ConfigurationManager.AppSettings["key"].ToString() %>';
for MVC application in .cshtml page try below
var key = '@System.Configuration.ConfigurationManager.AppSettings["key"].ToString()';