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;

  • 相关阅读:
    前端Ajax/JS/HTML+后端SpringMVC(二)
    前端Ajax/JS/HTML+后端SpringMVC(一)
    Redis 简介及应用
    项目中使用 MyBatis(二)
    L2d插件
    [转载] 栈内存和堆内存
    Hbase排错
    matplotlib中文乱码
    cocos2dx 一些好网站
    esclipe中接入SDK时引用另一个工程或Jar
  • 原文地址:https://www.cnblogs.com/flywing/p/8761715.html
Copyright © 2011-2022 走看看