添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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 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()';

Below code perfectly worked for me. I think you are missing namespace.

var apiUrl = '<%= System.Configuration.ConfigurationManager.AppSettings["url"].ToString() %>';
        alert(apiUrl);
                I really wonder if the solution mentioned above worked for any one, the correct answer should be what @darson1991 mentioned. which is  <script>     var apiUrl = '@System.Configuration.ConfigurationManager.AppSettings["url"]'; </script>
– 3not3
                Sep 12, 2017 at 18:34

index.html

<input id="getImageUrl" value="@System.Configuration.ConfigurationManager.AppSettings["OPMGTWebUrl"]" style="" />

index.js

var imageUrl = document.getElementById("getImageUrl").value;
                Hi and welcome to stackoverflow, and thank you for answering. While this code might answer the question, can you consider adding some explanation for what the problem was you solved, and how you solved it? This will help future readers to understand your answer better and learn from it.
– Plutian
                Feb 10, 2020 at 8:58
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.