在.NET Core中,IConfiguration 接口是用来读取配置数据的,包括从 appsettings.json 文件中读取。下面是一个如何在使用.NET Core时通过 IConfiguration 读取 appsettings.json 数据的示例。
首先,假设你的 appsettings.json 文件内容如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"MyCustomSettings": {
"ApiKey": "12345",
"BaseUrl": "https://api.example.com"
}
}
接下来,你需要在你的.NET Core项目中定义一个与 MyCustomSettings
部分相对应的C#类。这样,你就可以使用 IConfiguration
的 Get<T>()
方法来读取这些设置了。
public class MyCustomSettings
{
public string ApiKey { get; set; }
public string BaseUrl { get; set; }
}
然后,在你的Startup类或其他需要这些配置的类中,你可以通过构造函数注入 IConfiguration
,并使用它来获取 MyCustomSettings
的实例。
这里是一个在Star