AppsettingsHelp.cs 2.13 KB
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Options;

namespace Hh.Mes.Common.config
{
    /// <summary>
    /// AppsettingsHelp json操作类
    /// </summary>
    public class AppsettingsHelp
    {
        public T GetAppsettings<T>(string key) where T : class, new()
        {
            //https://www.cnblogs.com/zhouzangood/articles/2987088.html
            string keyDir = AppDomain.CurrentDomain.BaseDirectory ;

            IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(keyDir)
                .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
                .Build();
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }

        public IConfigurationRoot GetAppsettings()
        {
            string keyDir = AppDomain.CurrentDomain.BaseDirectory;
            var builder = new ConfigurationBuilder()
                .SetBasePath(keyDir)
                .AddJsonFile("appsettings.json");
            return builder.Build();
        }
    }


    public class AppSettings
    {
        private static IConfigurationSection appSection = null;

        /// <summary>
        /// 设置配置文件 Startup 注入 
        /// </summary>
        /// <param name="section"></param>
        public static void SetAppSetting(IConfigurationSection section)
        {
            appSection = section;
        }

        /// <summary>
        /// 获取配置文件 AppSettings.GetAppSeting("xxx")
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppSeting(string key)
        {
            return appSection.GetSection(key) != null ? appSection.GetSection(key).Value : "";
        }

    }
}