码迷,mamicode.com
首页 > Web开发 > 详细

.net core 2.0 mvc 获取配置信息

时间:2018-06-04 14:27:37      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:chain   legend   跳过   20px   canvas   直接   row   main   XML   

mvc_core_config

在.net core mvc中 配置文件格式更改为json且移除了ConfigurationManager.AppSettings[xmlkey]的方法,
那么,如何来获取配置信息呢?

第一步 将json文件添加到应用程序中

<default code>
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();

如果是使用默认的方法来启动的,则可以跳过此步

<reason>
    查看源码 在 CreateDefaultBuilder方法中已使用添加配置文件

      //配置信息处理 -- 用于第二步的读取配置信息
      .ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>) ((hostingContext, config) =>
      {
             //注入运行环境
            IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
              //加载配置文件
            config.AddJsonFile("appsettings.json", true, true).AddJsonFile(string.Format("appsettings.{0}.json", (object) hostingEnvironment.EnvironmentName), true, true);
          //根据运行环境加载相应文件
            if (hostingEnvironment.IsDevelopment())
            {
              Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
              if (assembly != (Assembly) null)
                config.AddUserSecrets(assembly, true);
            }

            config.AddEnvironmentVariables();
            if (args == null)
              return;
            config.AddCommandLine(args);
      }))

自定义添加配置文件请参考以上代码

第二步 读取配置信息

<code>

    <Startup>

    //由于在程序启动时已经配置了configuration 则可以直接通过构造方法获取配置信息

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

第三步 在Controller 获取配置信息

<code>

    <Startup>

        <method --> ConfigureServices>

        //添加选项
        services.AddOptions();

        //将配置信息进行DI注入
        services.Configure<AppSetting>(Configuration.GetSection(nameof(AppSetting)));

<相关方法说明>
    GetSection:
         key-value 取值
         类似于Dictionary取值的操作

    Configure:
        进行DI注入

        关键性代码:
            //进行DI注入  AddSingleton 全局共享一个   IOptionsChangeTokenSource<TOptions>  注入参数对应的type 
            services.AddSingleton<IOptionsChangeTokenSource<TOptions>>
                ((IOptionsChangeTokenSource<TOptions>) 
                new ConfigurationChangeTokenSource<TOptions>(name, config)
                );

            即实际上还是利用AddSingleton注入实现

        <source code>
            /// <summary>
            /// Registers a configuration instance which TOptions will bind against. 将配置实例作为option绑定到参数上
            /// </summary>
            /// <typeparam name="TOptions">The type of options being configured.</typeparam>
            /// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add the services to.</param>
            /// <param name="config">The configuration being bound.</param>
            /// <returns>The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> so that additional calls can be chained.</returns>
            public static IServiceCollection Configure<TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class
            {
              return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config);
            }

            /// <summary>
            /// Registers a configuration instance which TOptions will bind against.同上
            /// </summary>
            /// <typeparam name="TOptions">The type of options being configured.</typeparam>
            /// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add the services to.</param>
            /// <param name="name">The name of the options instance.</param>
            /// <param name="config">The configuration being bound.</param>
            /// <returns>The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> so that additional calls can be chained.</returns>
            public static IServiceCollection Configure<TOptions>(this IServiceCollection services, string name, IConfiguration config) where TOptions : class
            {
              if (services == null)
                throw new ArgumentNullException(nameof (services));
              if (config == null)
                throw new ArgumentNullException(nameof (config));
                    //进行DI注入  AddSingleton 全局共享一个   IOptionsChangeTokenSource<TOptions>  注入参数对应的type 
                    services.AddSingleton<IOptionsChangeTokenSource<TOptions>>((IOptionsChangeTokenSource<TOptions>) new ConfigurationChangeTokenSource<TOptions>(name, config));
              return services.AddSingleton<IConfigureOptions<TOptions>>((IConfigureOptions<TOptions>) new NamedConfigureFromConfigurationOptions<TOptions>(name, config));
            }

    <Controller>
        public abstract class BaseController : Controller
        {

            protected  AppSetting AppSetting { get; set; }

            protected BaseController(IOptions<AppSetting> option) => AppSetting = option.Value;

        }

    intro:由于在mvc经常会使用配置信息,于是我便将获取配置信息的相关处理封装在一个抽象控制器中,故只需要在使用配置信息的控制器中继承此控制器即可

然后就可以在控制器中通过AppSetting获取配置信息了

扩展说明

在Startup中直接获取配置文件:

public Startup(IApplicationEnvironment appEnv, IHostingEnvironment env) {

   _config = new ConfigurationBuilder()
            .AddJsonFile("config.json")
            .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
}

[https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration](https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration "官方教程")

备注:其中使用的AppSetting 即 我配置信息对应的实体类 【可根据实际情况进行命名】

欢迎各位大佬评论并指出我的错误 :)

author:monster

since:6/4/2018 11:12:45 AM

direction:.net core 2.0 mvc 配置文件的使用

 

.net core 2.0 mvc 获取配置信息

标签:chain   legend   跳过   20px   canvas   直接   row   main   XML   

原文地址:https://www.cnblogs.com/monster17/p/9132680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!