zoukankan      html  css  js  c++  java
  • asp.net core读取appsetting.json文件

    1、在Startup.cs文件中注入,ConfigureServices方法 

    services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));

    AppSetting.json文件

     "MyConfig": {
        "ResVersion": "1.0.2 Beta"
      },

    自定义类

    public class MyConfig
        {
            public string ResVersion { get; set; }
        }

    使用

    public class ValuesController : Controller
    {
            private readonly MyConfig _config;
    
            public ValuesController(IOptions<MyConfig> op)
            {
                _config = op.Value;
            }
    }

    2、读取指定节点下节点值。Nuget引入Microsoft.Extensitions.Configuration。

    自定义AppSettingHelper.cs。

    public class AppSettingsHelper
        {
        private static IConfigurationSection appSections = null;
    
            public static string AppSetting(string key)
            {
                string str = "";
                if (appSections.GetSection(key) != null)
                {
                    str = appSections.GetSection(key).Value;
                }
                return str;
            }
            public static void SetAppSetting(IConfigurationSection section)
            {
                appSections = section;
            }
    }

    在Startup.cs中ConfigureServices引入

    AppSettingsHelper.SetAppSetting(Configuration.GetSection("AppSettings"));

    AppSetting.json文件,只限AppSettings下一级节点

    "AppSettings": {
        "Url": "test"
      }

    使用

    var url = AppSettingsHelper.AppSetting("Url");

     3、不通过依赖注入形式。自定义AppSettingHelper.cs类。

     Nuget引入Microsoft.Extensitions.Configuration和Microsoft.Extensitions.Configuration.Json

    public class AppSettingsHelper
    {
            public static IConfiguration Configuration { get; set; }
            static AppSettingsHelper()
            {
                //ReloadOnChange = true 当appsettings.json被修改时重新加载            
                Configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
                .Build();
            }
    
            public static string SMSSign
            {
                get { return Configuration["SMS:SMSSign"]; }
            }
    }

    AppSetting.json配置文件

    "SMS": {
        "SMSSign": "测试"
      },
      

    使用直接调用 AppSettingHelper.SMSSign;

  • 相关阅读:
    【bzoj4591】[Shoi2015]超能粒子炮·改 Lucas定理
    【bzoj1604】[Usaco2008 Open]Cow Neighborhoods 奶牛的邻居 旋转坐标系+并查集+Treap/STL-set
    十分钟看懂图像语义分割技术
    命令行执行python模块时提示ImportError: No module named xxx
    python json与字典对象互相转换
    C#中json字符串的序列化和反序列化
    Python当前线程休眠1秒钟
    python之bytes和string
    Win32 基本文件读写操作
    C# 字符串与字节数组相互转换
  • 原文地址:https://www.cnblogs.com/flywing/p/8761715.html
Copyright © 2011-2022 走看看