【问题标题】:Set API URL based on Web.config appSettings根据 Web.config appSettings 设置 API URL
【发布时间】:2018-03-08 17:08:05
【问题描述】:

所以我有一个我继承的 Angular 应用程序,它将 API url 定义为一个常量变量并且它可以工作。然而,这有它的缺点,因为当我想指向部署 API、测试 API 和开发 API 时,我必须更改变量值。

有没有办法访问我的 web.config 文件以读取 appSettings 并返回 API URL? (我使用 XML 转换应用了不同的 API URL)。

我已经实现了一个解决方案,它从我的 Web 项目访问 API 控制器并以这种方式返回值,但我不确定这是否是正确的做法。

【问题讨论】:

    标签: c# .net angularjs api


    【解决方案1】:

    您可以将 web.config 中的值序列化为 JSON,并将它们添加到您的 JavaScript 可以读取和解析的 <script type="application/json"> 元素中。

    这是我能想到的最精简的例子。您可能希望更好地封装如何从服务器代码编写此代码以及如何从 JavaScript 读取它(并想出更好的名称。)

    首先,在您的 web.config 中,定义包含您要传递给 JavaScript 的键/值对的部分:

    <?xml version="1.0" encoding="utf-8"?>
        <configuration>
          <configSections>
            <section name="jsConfigurationValues" 
              type="System.Configuration.NameValueSectionHandler" />
          </configSections>
    
          <jsConfigurationValues>
            <add key="someValue" value="a" />
            <add key="apiUrl" value="http://theurl" />
          </jsConfigurationValues>
    
          <!-- the rest of your web.config -->
    
        </configuration>
    

    在 web 表单的代码隐藏中是这个函数。

    protected string JavascriptConfigurationValues()
    {
        var configurationValues =
            (NameValueCollection)ConfigurationManager.GetSection("jsConfigurationValues");
        var dictionary = new Dictionary<string, string>();
        foreach(var key in configurationValues.AllKeys) 
            dictionary.Add(key, configurationValues[key]);
        return JsonConvert.SerializeObject(dictionary);
    }
    

    在 web 表单的标记中是这样的:

    <script type="application/json" id="mySettings">
        <% =JavascriptConfigurationValues() %>
    </script>
    

    (您可以将其中的部分或全部放在 UserControl 中或以其他方式封装。)

    此脚本读取 JSON 并将其分配给变量:

    var mySettings = JSON.parse(document.getElementById("mySettings").textContent);
    

    现在可以访问了:

    var apiUrl = mySettings.apiUrl;
    

    【讨论】:

    • 这里有一个缺失的部分,这就是将这个值导入到你的 Angular 中的 Angularish 方式。也许您最好从相对 URL 调用一个 API 以获取剩余的一组特定于环境的绝对 URL 并让浏览器缓存它。
    • 感谢 Scott 的回复,我将尝试使用此解决方案,希望能解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2016-12-27
    • 2011-09-11
    • 1970-01-01
    • 2019-05-21
    相关资源
    最近更新 更多