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);
	}
}
相关推荐
锋君20 小时前
Orcale数据库在Asp.Net Core环境下使用EF Core 生成实体
数据库·后端·oracle·asp.net
Aevget2 天前
DevExtreme JS & ASP.NET Core v25.2预览 - DataGrid/TreeList全新升级
开发语言·javascript·asp.net·界面控件·ui开发·devextreme
Aevget2 天前
界面控件DevExpress JS & ASP.NET Core v25.1 - 全新的Stepper组件
javascript·asp.net·界面控件·devexpress·ui开发
kkk_皮蛋3 天前
信令是什么?为什么 WebRTC 需要信令?
后端·asp.net·webrtc
2301_800256114 天前
第十一章中的函数解读(1)
后端·asp.net
武藤一雄4 天前
[.NET] 中 System.Collections.Generic命名空间详解
windows·微软·c#·asp.net·.net·.netcore
0和1的舞者4 天前
SpringBoot配置文件
java·spring boot·后端·web·配置·spirng
William_cl6 天前
【CSDN 专栏】C# ASP.NET控制器过滤器:自定义 ActionFilterAttribute 实战(避坑 + 图解)
c#·asp.net·状态模式
William_cl6 天前
【CSDN 专栏】C# ASP.NET Razor 视图引擎实战:.cshtml 从入门到避坑(图解 + 案例)
开发语言·c#·asp.net
靓仔建7 天前
在asp.net web应用程序,老是访问同一个Handler1.ashx
后端·asp.net·一般处理程序