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;

  • 相关阅读:
    jQuery 自执行函数
    IRelationalOperator空间关系接口简介
    9.2 空间拓扑运算[转]
    解决关于ArcGIS10.2服务手动启动的问题
    Multipart to single part feature
    Multipart polyline to single part lines
    VS2015 C#6.0 中的没有实现/支持的特性
    VS2015 C#6.0 中的那些新特性
    ArcGIS中各种合并要素(Union、Merge、Append、Dissolve)的异同点分析 转载
    FME2010 案例分析: 动态批量转换
  • 原文地址:https://www.cnblogs.com/flywing/p/8761715.html
Copyright © 2011-2022 走看看