ASP.NET读取配置文件的多种方式详解

ASP.NET教程 2025-08-22

目录

  • IConfiguration
  • 通过GetValue方法获取
  • 通过GetSection方法获取
  • 使用委托来配置选项

ASP.NET Core项⽬默认的配置⽂件是appsettings.json,创建项⽬时就会⾃动⽣成这个文件,我们可以将⼀些配置信息存放在这个配置⽂件中,这样做的好处是当我们修改配置⽂件 时,不在需要重启应⽤,可以实现热更新。

{
 "Logging": {
 "LogLevel": {
 "Default": "Information",
 "Microsoft.AspNetCore": "Warning"
 }
 },
 "AllowedHosts": "*",
 "msg": "hello world"
}

IConfiguration

个路由终结点来演⽰如何读取这个配置

app.MapGet("config", (IConfiguration configuration) =
{
 return configuration["msg"] + "_" +
     configuration["Logging:LogLevel:Default"];
});

通过IOC注⼊IConfiguration对象,我们就可以访问不同节点的配置了,如果是单层节点, 通过configuration[msg]的⽅式进⾏访问,如果是多层级,则通过 configuration[Logging:LogLevel:Default]来访问

通过GetValue方法获取

app.MapGet("config", (IConfiguration configuration) =
{
     return configuration.GetValuestring("msg");
});

GetValue⽆法读取对象,会报异常

通过GetSection方法获取

app.MapGet("config", (IConfiguration configuration) =
{
     return configuration.GetSection("msg").Value;
});

读取对象

app.MapGet("config", (IConfiguration configuration) =
{
     return configuration.GetSection("Person").GetPerson();
});

使用委托来配置选项

先定义⼀个实体:

public class Person
{
     public string Name { get;set; }
     public int Age { get;set; }
}

配置如下:

"Person": {
 "Name": "张三",
 "Age": 18
}

注册配置:

builder.Services.ConfigurePerson
(builder.Configuration.GetSection("Person"));

使⽤配置:

app.MapGet("config", (IOptionsPerson options) =
{
     return $"{options.Value.Name},{options.Value.Age}";
});

到此这篇关于ASP.NET读取配置文件的多种方式详解的文章就介绍到这了,更多相关ASP.NET读取配置文件内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

您可能感兴趣的文章:
  • ASP.Net Core读取配置文件的三种方法小结
  • ASP.NET CORE读取json格式配置文件
  • ASP.NETCore读取配置文件
  • Asp.net Core与类库读取配置文件信息的方法
  • 如何在ASP.NET Core类库项目中读取配置文件详解
  • asp.net 读取配置文件方法