[英]How can I read key value from web.config in javascript file?
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.我正在尝试从 web.config 文件中读取 apiUrl 键值,以便我可以利用 .net 转换配置来管理不同环境中的部署。 Here is my Webconfig code:这是我的 Webconfig 代码:
<appSettings>
<add key="url" value="http://localhost:6299/api/"
</appSettings>
and in the plain js file I have this code:在普通的 js 文件中,我有以下代码:
var apiUrl = '<%=ConfigurationManager.AppSettings["url"].Tostring()
%>'.
It is not giving the url value.它没有给出 url 值。 How can I read web.config value in javascript file?如何读取 javascript 文件中的 web.config 值?
"In the plain js file" “在普通的 js 文件中”
do you mean a file ending in .js ?你的意思是一个以 .js 结尾的文件吗?
.js files are not parsed server-side so the <%=
values are not converted. .js 文件不会在服务器端解析,因此<%=
值不会被转换。 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'.这适用于另一个答案(“为我工作”),因为它们将在 .aspx/.cshtml 文件中而不是“普通的 .js 文件”中。
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.您需要将代码移动到 .aspx/.cshtml,或者您需要通过 .aspx/.cshtml 文件中的函数参数将 url 值传递给您的 js(例如)。
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下面的代码在 ASP.Net webforms 应用程序中对我有用,但在 MVC 应用程序中不起作用
var key = '<%= System.Configuration.ConfigurationManager.AppSettings["key"].ToString() %>';
for MVC application in .cshtml page try below对于 .cshtml 页面中的 MVC 应用程序,请尝试以下
var key = '@System.Configuration.ConfigurationManager.AppSettings["key"].ToString()';
Below code perfectly worked for me.下面的代码非常适合我。 I think you are missing namespace.我认为您缺少命名空间。
var apiUrl = '<%= System.Configuration.ConfigurationManager.AppSettings["url"].ToString() %>';
alert(apiUrl);
index.html索引.html
<input id="getImageUrl" value="@System.Configuration.ConfigurationManager.AppSettings["OPMGTWebUrl"]" style="display:none" />
index.js索引.js
var imageUrl = document.getElementById("getImageUrl").value;
以下行将返回URL
值。
var apiUrl = '<%=ConfigurationManager.AppSettings["url"]%>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.