10.ASP.NET Core appsettings.json 文件

721 阅读2分钟

本篇文章,我们将讨论 ASP.NET Core 项目中appsettings.json文件的重要性。

image.png

在传统的ASP.NET 版本中中,我们将应用程序配置设置(例如数据库连接字符串)存储在web.config文件中。 在 ASP.NET Core 中, 应用程序配置设置可以来自以下不同的配置源。

  • 文件(appsettings.json, appsettings.{Environment}.json)不同环境下,对应不同的托管环境。
  • User secrets (用户机密)
  • Environment variables (环境变量)————launchSettings.json文件
  • Command-line arguments (命令行参数)

appsettings.json文件: 我们的项目是通过 ASP.NET Core 预制的"空"模板创建的,所以我们的项目中已经有一个 appsettings.json 的文件了。 我们可以对文件进行如下修改,补充一个MyKey的键值对:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MyKey": " appsettings.json中Mykey的值"
}

访问配置信息

若要访问  "Startup "  类中的配置信息, 请注入框架提供的 IConfiguration服务。Startup类位于 startup. cs 文件中。

public class Startup
    {
        //依赖注入
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
           
            app.UseRouting();
            
            app.UseAuthorization();

            app.Run(async (context) =>
            {
                ////获取进程名
                //var processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;

                var configVal = Configuration["MyKey"];
                await context.Response.WriteAsync(configVal);
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
           
        }
    }

依赖注入

在以前版本的 ASP.NET 中,依赖注入是可选的,要配置它,我们必须使用像 Ninject,autofac、castle windsor 等第三方框架。

在 ASP.NET Core 中, 依赖注入是不可或缺的一部分。依赖注入能使我们能够创建低耦合、可扩展且易于测试的系统。

ASP.NET Core IConfiguration 服务

  • IConfiguration 服务是为了从 ASP.NET Core 中的所有各种配置源读取配置信息而设计的。
  • 如果在多个配置源中具有相同密钥名称的配置设置,简单来说就是重名了,则后面的配置源将覆盖先前的配置源  。
  • 静态类WebHostCreateDefaultBuilder()方法在应用程序启动时会自动去调用,按特定顺序读取配置源。
  • 要查看配置源的读取顺序,请查看以下链接上的ConfigureAppConfiguration()方法 github.com/aspnet/Meta…

检查文件后,您将看到,以下是读取各种配置源的默认顺序

  1. appsettings.json,
  2. appsettings.{Environment}.json
  3. 用户机密
  4. 环境变量
  5. 命令行参数