从 ASP.NET Core 应用程序中的 .json 文件检索 AppSettings
本指南演示如何访问 ASP.NET Core 应用程序中 .json 文件中存储的配置设置。
1。启动类中的配置设置:
以下代码片段将应用程序配置为从 appsettings.json
读取设置。 请注意使用 reloadOnChange: true
进行动态更新。
public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } // ... rest of your Startup class ... }
2。依赖注入配置:
此步骤为您的自定义配置对象启用依赖注入。
public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<MyConfig>(Configuration.GetSection("MyConfig")); // ... other service configurations ... }
3。定义配置对象:
创建一个类来表示您的配置设置。
public class MyConfig { public string Token { get; set; } }
4。将配置注入控制器:
将 IOptions<MyConfig>
接口注入控制器以访问配置值。
public class HomeController : Controller { private readonly IOptions<MyConfig> config; public HomeController(IOptions<MyConfig> config) { this.config = config; } public IActionResult Index() => View(config.Value); }
5。访问配置值:
使用注入的 config
对象访问您的设置。
//Example usage within the HomeController's action method: string myToken = config.Value.Token;
或者,您可以直接从 IConfigurationRoot
访问设置(尽管通常首选依赖注入)。
var token = Configuration["MyConfig:Token"];
重要注意事项:
appsettings.json
文件(或适当命名的配置文件)位于正确的目录中。Microsoft.Extensions.Configuration.Json
NuGet 包以启用 JSON 配置支持。"MyConfig"
和 "Token"
替换为您的特定配置部分和属性名称。此修订后的解释提供了一种更清晰、更结构化的方法来从 ASP.NET Core 中的 .json 文件访问 AppSettings。 使用依赖注入被强调为最佳实践。
以上是如何从 ASP.NET Core 中的 .json 文件访问 AppSettings?的详细内容。更多信息请关注PHP中文网其他相关文章!