栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

ASP.NET Core自定义配置文件

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ASP.NET Core自定义配置文件

新建Configuration类库专门获取各个配置信息

NuGet安装Microsoft.NETCore.App和Microsoft.AspNetCore.App

在类库中新建SysConfig类

using System.IO;
using Configuration.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Configuration
{
    /// 
    /// 系统配置
    /// 
    public static class SysConfig
    {
        //=================== private fields ======================
        #region fields      
        private static IConfiguration m_webCongfig;
        #endregion



        //=================== public properties ===================
        #region webCongfig 描述
        /// 
        /// 描述
        /// 
        public static IConfiguration WebCongfig => m_webCongfig;
        #endregion



        //=================== public metod ========================
        #region ConfigurationInit 设置配置文件
        /// 
        /// 设置配置文件
        /// 
        /// 
        public static void ConfigurationInit(IHostingEnvironment env)
        {
            //配置文件:如果同个配置在多个配置文件中同时存在,则最后的配置文件里的配置生效
            var _builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json",optional: true,reloadOnChange: true)//从json文件中取值,reloadOnChange:当配置文件发生变化后,是否重新加载配置
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional: true);//在开发环境中会使用“appsettings.Development.json”的配置文件,并用其中的值覆盖当前存在的其他值。

            _builder.AddEnvironmentVariables();//从环境变量中取值
            m_webCongfig = _builder.Build();
        }
        #endregion

        #region DependencyInjectionServices 将配置信息注入到对象中
        /// 
        /// 将配置信息注入到对象中
        /// 
        /// 
        public static void DependencyInjectionServices(IServiceCollection services)
        {
            if (m_webCongfig == null)
            {
                return;
            }

            services.AddOptions();
            //通过Microsoft.Extensions.Options.ConfigurationExtensions来配置TestSetting的值,大小写不敏感
            services.Configure(SysConfig.WebCongfig);

            //通过代码来配置TestSetting的值
            services.Configure(set =>
            {
                set.Lch = "LICH";
            });

            //获取子设置
            services.Configure(SysConfig.WebCongfig.GetSection("Logging")?.GetSection("LogLevel"));

            services.Configure(SysConfig.WebCongfig.GetSection("不存在设置")?.GetSection("LogLevel"));
        }
        #endregion        
    }
}

再新建TestSetting和LogLevelSetting模型类,用来测试存放配置
TestSetting

namespace Configuration.Model
{
    public class TestSetting
    {
        //=================== construct function ==================	
        #region construct 测试配置模型
        /// 
        /// 测试配置模型
        /// 
        public TestSetting()
        {
        }
        #endregion



        //=================== private fields ======================
        #region fields      
        private string m_lch;
        private LogLevelSetting m_logLevelSetting;
        #endregion



        //=================== public properties ===================
        #region lch
        /// 
        ///
        /// 
        public string Lch
        {
            get => this.m_lch;
            set => this.m_lch = value;
        }
        #endregion

        #region logLevelSetting
        /// 
        ///
        /// 
        public LogLevelSetting LogLevelSetting
        {
            get => this.m_logLevelSetting;
            set => this.m_logLevelSetting = value;
        }
        #endregion
    }
}

LogLevelSetting

namespace Configuration.Model
{
    public class LogLevelSetting
    {
        //=================== construct function ==================	
        #region construct 日志等级配置
        /// 
        /// 日志等级配置
        /// 
        public LogLevelSetting()
        {
        }
        #endregion



        //=================== private fields ======================
        #region fields      
        private string m_default;
        private string m_system;
        private string m_microsoft;
        #endregion



        //=================== public properties ===================
        #region default
        /// 
        /// 
        /// 
        public string Default
        {
            get => this.m_default;
            set => this.m_default = value;
        }
        #endregion

        #region system
        /// 
        ///
        /// 
        public string System
        {
            get => this.m_system;
            set => this.m_system = value;
        }
        #endregion

        #region microsoft
        /// 
        ///
        /// 
        public string Microsoft
        {
            get => this.m_microsoft;
            set => this.m_microsoft = value;
        }
        #endregion
    }
}

在Startup调用初始化配置和注册服务
Startup 构造方法添加SysConfig.ConfigurationInit(env);

    #region Startup 构造
        /// 
        /// 构造
        /// 
        /// 
        public Startup(IConfiguration configuration,IHostingEnvironment env)
        {
            this.Configuration = configuration;//其他
            SysConfig.ConfigurationInit(env);
        }
        #endregion

在ConfigureServices方法内添加SysConfig.DependencyInjectionServices(services);

   #region ConfigureServices 用于定义应用所使用的服务
        /// 
        /// 用于定义应用所使用的服务(ASP.NET Core MVC、Entity Framework Core、Identity等)
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// 
        public void ConfigureServices(IServiceCollection services)
        {
            SysConfig.DependencyInjectionServices(services);
            StaticFilesConfigureServices(services);//其他
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);//其他
        }
        #endregion

最后在对应Test控制器内调用

using Configuration.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace WebApplication1.Controllers
{
    public class TestController:Controller
    {

        //=================== construct function ==================	
        #region construct construct
        /// 
        /// construct
        /// 
        public TestController(
            IOptions testSetting,
            IOptions logLevelSetting)
        {
            this.m_testSetting = testSetting;
            this.m_logLevelSetting = logLevelSetting;
        }
        #endregion



        //=================== private fields ======================
        #region fields      
        private readonly IOptions m_testSetting;
        private readonly IOptions m_logLevelSetting;
        #endregion


        //=================== public metod ========================
        #region Index
        /// 
        /// 
        /// 
        /// 
        public IActionResult Index()
        {
            var _aa = this.m_testSetting.Value;
            var _bb = this.m_logLevelSetting.Value;
            return this.View();
        }
        #endregion
    }
}

结果:
this.m_testSetting.Value

this.m_logLevelSetting.Value

配置json
appsettings.Development.json

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985202.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号