.NET 6(Core)步步学-读取 appsettings.json 配置文件

作者:vkvi 来源:ITPOW(原创) 日期:2022-4-1

.NET Framework 中配置文件是 web.config,在 .NET Core 中抛弃了这种 XML 格式,采用 JSON 格式,位于 appsettings.json

咱们添加两个属性

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

  "ItpowKey": "yes",
  "Itpow": {
    "SiteName": "itpow"
  }
}

如上 Itpow 开头的,都是我们添加的。

试试在 Program.cs 中如何读取

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var itpowKey = builder.Configuration.GetSection("ItpowKey").Value;

var app = builder.Build();
app.MapGet("/", () => itpowKey);
app.Run();

首先利用 builder.Configuration.GetSection("ItpowKey").Value 读取出来。

然后用 app.MapGet("/", () => itpowKey),当我们访问应用根目录时,就会输出其值。

这里是不区分大小写的。

咱们还有一个 Key,这样读:GetSection("Itpow:SiteName"),或者:GetSection("Itpow")["SiteName"]。

在 Controller 中如何读取呢?

我们写 Web API,大多是派生自 ControllerBase 的(如果有 View 需要,则派生自 Controller)

[HttpGet]
public string Get()
{
	var config = new ConfigurationBuilder()
			  .AddInMemoryCollection()
			  .SetBasePath(Directory.GetCurrentDirectory())
			  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
			  .Build();
	return config.GetSection("ItpowKey").Value;
}

相关阅读

相关文章