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);
	}
}
相关推荐
一枚小小程序员哈1 天前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
做一位快乐的码农2 天前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
一枚小小程序员哈4 天前
基于C#、.net、asp.net的心理健康咨询系统设计与实现/心理辅导系统设计与实现
c#·asp.net·.net
Archy_Wang_14 天前
ASP.NET 上传文件安全检测方案
后端·c#·asp.net
界面开发小八哥6 天前
DevExpress ASP.NET Web Forms v25.1新版本开发环境配置要求
c#·asp.net·界面控件·devexpress·ui开发
Vdeilae13 天前
IIS 让asp.net core 项目一直运行
java·服务器·asp.net
woflyoycm14 天前
.net6的webapi项目统一封装返回值
c#·asp.net·.net
胡西风_foxww16 天前
Vue2 项目实现 Gzip 压缩全攻略:从配置到部署避坑指南
nginx·部署·vue2·配置·gzip·压缩·攻略
我来整一篇17 天前
ASP.NET Core中使用NLog和注解实现日志记录
后端·asp.net
ArabySide17 天前
【ASP.NET Core】探讨注入EF Core的DbContext在HTTP请求中的生命周期
后端·http·asp.net·asp.net core·efcore