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 天前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
假装我不帅2 天前
rider开发asp.net webform项目
android·okhttp·asp.net
实战项目2 天前
ASP.NET实现的房产中介管理系统设计
后端·asp.net
William_cl5 天前
ASP.NET Core 视图组件:从入门到避坑,UI 复用的终极方案
后端·ui·asp.net
William_cl6 天前
ASP.NET Core ViewData:弱类型数据交互的精髓与避坑指南
后端·asp.net·交互
Net蚂蚁代码7 天前
【如何在ASP.Net Core中使用 IHostedService的方法】执行自动服务运行
后端·asp.net
Caco.D7 天前
Aneiang.Pa.News:属于你自己的全平台热点聚合阅读器
爬虫·asp.net·aneiang.pa·热榜新闻
咖丨喱8 天前
【解析并缓存 P2P_ATTR_DEVICE_INFO】
缓存·asp.net·p2p
咖丨喱8 天前
【解决Miracast出现组形成失败问题】
后端·asp.net
智商偏低8 天前
ABP 框架中的 HttpContextWebClientInfoProvider
后端·asp.net