ASP.NET Core_配置文件访问和自定义强类型访问

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Star_Inori/article/details/81435338

用于ASP.NET CORE的配置文件

应用程序settings通常存储在appsettings.json中,但是configuration更加灵活,可以选择多个JSON或XML文件以及环境变量进行配置

具体来说,默认会配置5个Provider

  • MemoryConfigurationProvider
  • JsonConfigurationProvider (appsetttings.json)
  • JsonConfigurationProvider (appsettings.{environment}.json)
  • EnvironmentVariablesConfigurationProvider
  • CommandLineConfigurationProvider

通过Startup类的造函数注入IConfiguration访问

访问configuration的值可以通过Startup类通过构造函数注入IConfiguration接口和使用Get方法接收configuration

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public IConfiguration Configuration { get; }
    ...
}

创建配置文件appsettings.json

{
  "SampleSettings": {
    "Setting1": "Value1"
  },
  "AppSettings": {
    "setting2": "Value2",
    "Setting3": "Value3",
    "SubSection1": {
      "Setting4": "Value4"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

读取配置

可以使用IConfiguration接口读取配置。

namespace ASPCoreSamples
{
    public class ConfigurationSample
    {
        private readonly IConfiguration _configuration;

        /// <summary>
        /// ConfigurationSample通过依赖注入访问IConfiguration接口。
        /// </summary>
        /// <param name="configuration"></param>
        public ConfigurationSample(IConfiguration configuration) =>
            _configuration = configuration;

        /// <summary>
        /// 访问Setting,_configuration.GetSection("SampleSettings")["Setting1"];
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ShowApplicationSettingsAsync(HttpContext context)
        {
            //通过GetSection获得配置文件中的Sections,通过索引器获得Settings,
            string settings = _configuration.GetSection("SampleSettings")["Setting1"];
            await context.Response.WriteAsync(settings.Div());
        }

        /// <summary>
        /// 访问Setting,借助冒号。_configuration["SampleSettings:Setting1"];
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ShowApplicationSettingsUsingColonsAsync(HttpContext context)
        {
            string settings = _configuration["SampleSettings:Setting1"];
            await context.Response.WriteAsync(settings.Div());
        }

        /// <summary>
        /// 使用GetConnectionString直接访问数据库连接串
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ShowConnectionStringSettingAsync(HttpContext context)
        {
            string connectionString = _configuration.GetConnectionString("DefaultConnection");
            await context.Response.WriteAsync(connectionString.Div());
        }

    }
}

使用自定义强类型类访问Configuration

还可以创建一个对configuration值进行强类型访问的类。创建AppSettings和SubSection1类,其属性名称直接映射到配置文件中的键。

namespace ASPCoreSamples
{
    public class SubSection1
    {
        public string Setting4 { get; set; }
    }

    public class AppSettings
    {
        public string Setting2 { get; set; }
        public string Setting3 { get; set; }
        public SubSection1 SubSection1 { get; set; }
    }

    public class ConfigurationSample
    {
        ...
        /// <summary>
        /// 调用泛型Get方法和AppSettings类得到自定义类映射的自定义configuration类型
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ShowApplicationSettingsStronglyTyped(HttpContext context)
        {
            AppSettings settings = _configuration.GetSection("AppSettings").Get<AppSettings>();
            await context.Response.WriteAsync($"setting 2:{settings.Setting2}" +
                $"setting 3:{settings.Setting3}" +
                $"setting 4:{settings.SubSection1.Setting4}".Div());
        }
    }
}

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        #region 自定义类、自定义configuration
        services.AddTransient<ConfigurationSample>();
        #endregion

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        ...
        PathString remainingPath;
        app.MapWhen(context => context.Request.Path.StartsWithSegments("/Configuration", out remainingPath), configurationApp =>
        {
            configurationApp.Run(async context =>
            {
                var configSample = app.ApplicationServices.GetService<ConfigurationSample>();
                if (remainingPath.StartsWithSegments("/appsettings"))
                {
                    await configSample.ShowApplicationSettingsAsync(context);
                }
                else if (remainingPath.StartsWithSegments("/colons"))
                {
                    await configSample.ShowApplicationSettingsUsingColonsAsync(context);
                }
                else if (remainingPath.StartsWithSegments("/database"))
                {
                    await configSample.ShowConnectionStringSettingAsync(context);
                }
                else if (remainingPath.StartsWithSegments("/stronglytyped"))
                {
                    await configSample.ShowApplicationSettingsStronglyTyped(context);
                }
            });
        });
    }
}

结果

Value1//appsettings
Value1//colons
Server=(localdb)\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true//database
setting 2:Value2setting 3:Value3//stronglytyped
setting 4:Value4//stronglytyped
展开阅读全文

没有更多推荐了,返回首页