外部配置源,例如 JSON 文件,在 Web 开发中经常使用。 与旧版本不同,ASP.NET Core 提供了访问此数据的强大方法。本指南演示如何从 JSON 文件检索 AppSettings 值。
首先,使用您的键值对创建一个 Config.json
文件(例如,在 appsettings
文件夹中):
<code class="language-json">{ "AppSettings": { "token": "1234" } }</code>
此文件存储您将在代码中访问的配置数据。
在应用程序的 Startup.cs
文件中,配置 ConfigurationBuilder
:
<code class="language-csharp">public class Startup { public IConfiguration Configuration { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings/Config.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } // ... rest of your Startup class }</code>
要在控制器中使用这些设置,请注入 IConfiguration
对象:
<code class="language-csharp">public class HomeController : Controller { private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } public IActionResult Index() { var token = _configuration["AppSettings:token"]; return View(token); } }</code>
使用键路径“AppSettings:token”检索值非常简单。
对于 ASP.NET Core 2.0 及更高版本,选项模式提供了一种更加结构化的方法。
定义一个代表您的配置的类:
<code class="language-csharp">public class AppSettings { public string Token { get; set; } }</code>
在Startup.cs
中,配置并注入IOptions<AppSettings>
对象:
<code class="language-csharp">services.AddOptions<AppSettings>() .Configure<IConfiguration>((settings, configuration) => { configuration.GetSection("AppSettings").Bind(settings); });</code>
现在,在你的控制器中:
<code class="language-csharp">public class HomeController : Controller { private readonly IOptions<AppSettings> _appSettings; public HomeController(IOptions<AppSettings> appSettings) { _appSettings = appSettings; } public IActionResult Index() { var token = _appSettings.Value.Token; return View(token); } }</code>
与之前的方法相比,此方法提供了类型安全性并提高了可维护性。 这是较新的 ASP.NET Core 项目的首选方法。
以上是如何从 ASP.NET Core 中的 JSON 文件读取 AppSettings 值?的详细内容。更多信息请关注PHP中文网其他相关文章!