zoukankan      html  css  js  c++  java
  • .NET Core2.1获取自定义配置文件信息

    实现

    注:需要NuGet引入:Microsoft.Extensions.Options.ConfigurationExtensions

    ①我们再配置文件appsettings.json中 新增自定义API Json如下:

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "API": {
        "Url": "http://localhost:8080/",
        "getclub": "api/club"
      } 
    }

    ②然后我们定义一个静态类,再类中申明一个IConfigurationSection 类型变量

    private static IConfigurationSection _appSection = null;

    ③写一个AppSetting静态方法获取到配置的Value项,代码如下:

           public static string AppSetting(string key)
            {
                string str = string.Empty;
                if (_appSection.GetSection(key) != null)
                {
                    str = _appSection.GetSection(key).Value;
                }
                return str;
            }

    ④需要设置IConfigurationSection初始值,如下:

           public static void SetAppSetting(IConfigurationSection section)
            {
                _appSection = section;
            }

    ⑤然后写一个根据不同Json项读取出对应的值即可:

      public static string GetSite(string apiName)
      {
          return AppSetting(apiName);
      }

    ⑥有了以上几个步骤,基本上读取代码已经全部写完,剩下最后一个最重要的步骤,将要读取的Json文件配置到Startup.cs的Configure方法中,如下:

    这样,我们就可以很轻松的获取到我们想要的配置项了,整段CS代码如下:

        /// <summary>
        /// 配置信息读取模型
        /// </summary>
        public static class SiteConfig
        {
            private static IConfigurationSection _appSection = null;
    
            /// <summary>
            /// API域名地址
            /// </summary>
            public static string AppSetting(string key)
            {
                string str = string.Empty;
                if (_appSection.GetSection(key) != null)
                {
                    str = _appSection.GetSection(key).Value;
                }
                return str;
            }
    
            public static void SetAppSetting(IConfigurationSection section)
            {
                _appSection = section;
            }
    
            public static string GetSite(string apiName)
            {
                return AppSetting(apiName);
            }
        }

    最后 ,我们来跑一下演示效果如下:

  • 相关阅读:
    OpenGL的glTranslatef平移变换函数详解
    OpenGL的glRotatef旋转变换函数详解
    OpenGL的GLUT初始化函数[转]
    OpenGL的GLUT事件处理(Event Processing)窗口管理(Window Management)函数[转]
    OpenGL的GLUT注册回调函数[转]
    OpenGL的gluLookAt和glOrtho的关系
    OpenGL的glClearColor和glClear改变背景颜色
    OpenGL的gluPerspective和gluLookAt的关系[转]
    OpenGL的glOrtho平行投影函数详解[转]
    OpenGL的glViewport视口变换函数详解[转]
  • 原文地址:https://www.cnblogs.com/qingfenglin/p/10883083.html
Copyright © 2011-2022 走看看