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);
	}
}
相关推荐
SunkingYang2 天前
iPhone 17系列包含哪些版本,各版本又有哪些配置,硬件、功能、性能、价格详细介绍
iphone·配置·硬件·性能·区别·价格·iphone17
智商偏低2 天前
ASP.NET Core 中的简单授权
后端·asp.net
core5124 天前
Hive实战(一)
数据仓库·hive·hadoop·架构·实战·配置·场景
是萝卜干呀4 天前
IIS 部署 asp.net core 项目时,出现500.19、500.31问题的解决方案
后端·iis·asp.net·hosting bundle
爱喝水的鱼丶5 天前
SAP-MM:SAP核心组织单元:工厂(Plant)全面学习指南及配置图解
学习·sap·abap·配置·工厂·mm模块
速易达网络6 天前
ASP.NET MVC 连接 MySQL 数据库查询示例
数据库·asp.net·mvc
智商偏低7 天前
ASP.NET Core 身份验证概述
后端·asp.net
冷冷的菜哥7 天前
ASP.NET Core使用MailKit发送邮件
后端·c#·asp.net·发送邮件·mailkit
冷冷的菜哥10 天前
ASP.NET Core文件分片上传
c#·asp.net·asp.net core·文件分片上传
前端世界13 天前
ASP.NET 实战:用 SqlCommand 打造一个安全的用户注册功能
后端·安全·asp.net