Asp.Net Core 中使用配置文件

本文参考微软文档:ASP.NET Core 中的配置

ASP.NET Core 中的应用程序配置是使用一个或多个配置程序提供程序执行的。

配置提供程序使用各种配置源从键值对读取配置数据:

  • 设置文件,例如 appsettings.json
  • 环境变量
  • Azure Key Vault
  • Azure 应用配置
  • 命令行参数
  • 已安装或已创建的自定义提供程序
  • 目录文件
  • 内存中的 .NET 对象

这里主要介绍使用设置文件,设置文件包含一组名称类似的文件:appsettings.json,appsettings.{Environment}.json

其中,Environment 取值可以是任意值,但是框架提供了下列三个值:

默认的 JsonConfigurationProvider 会按以下顺序加载配置:

  1. appsettings.json
  2. appsettings.{Environment}.json:例如,appsettings.Production.jsonappsettings.Development.json 文件。 文件的环境版本是根据 IHostingEnvironment.EnvironmentName 加载的。

appsettings.{Environment}.json 值替代 appsettings.json 中的键。 例如,默认情况下:

  • 在开发环境中,appsettings.Development.json 配置会覆盖在 appsettings.json 中找到的值。
  • 在生产环境中,appsettings.Production.json 配置会覆盖在 appsettings.json 中找到的值。 例如,在将应用部署到 Azure 时。

经测试,通过IDE直接启动时,使用的是appsettings.Development.json文件,而发布后的程序启动时,使用的则是 appsettings.Production.json文件。

在代码中使用配置文件

通过依赖注入的方式配置Configuration属性,然后通过GetSection方法访问键值对。

cs 复制代码
public partial class AdminContext : DbContext
{
    public AdminContext(IConfiguration configuration)
    {
		Configuration = configuration;
    }
    public AdminContext(DbContextOptions<AdminContext> options, IConfiguration configuration)
        : base(options)
    {
		Configuration = configuration;
    }
	private readonly IConfiguration Configuration;
	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		string? host = Configuration.GetSection("DBHost").Value;
        string? port = Configuration.GetSection("DBPort").Value;
        string? userid = Configuration.GetSection("DBUser").Value;
        string? password = Configuration.GetSection("DBPasswd").Value;
        string connectString = $"host={host};port={port};database=Admin; userid={userid};password={password};";
		optionsBuilder.UseMySQL(connectString);
	}
}
相关推荐
剑锋所指,所向披靡!3 天前
计算机网络之应用层(HTTP)
计算机网络·http·asp.net
无风听海4 天前
深入理解 ASP.NET Core Authentication Scheme 体系
运维·云计算·asp.net
勿芮介4 天前
【开发技术】Asp.NetCore的管道和中间件
后端·asp.net
步步为营DotNet4 天前
深入.NET 11:ASP.NET Core 10 在构建高可用分布式系统的关键技术与实践
asp.net·.net·wpf
无风听海5 天前
ASP.NET Core Session 机制深度解析
后端·asp.net
无风听海8 天前
深入理解 ASP.NET Core 中的 UseRouting 与 UseEndpoints
后端·asp.net
无风听海8 天前
ASP.NET Core Minimal API 深度解析
后端·asp.net
步步为营DotNet9 天前
解锁.NET 11 新境:ASP.NET Core 10 在微服务安全通信的深化与实践
微服务·asp.net·.net
无风听海10 天前
深入理解 ASP.NET Core 中的 IActionResult
后端·asp.net
无风听海10 天前
ASP.NET Core Results<T1, T2>深度解析
后端·asp.net