如何从ASP.NET Core中的Config.json中读取AppSettings值
我已经在Config.json中设置了我的AppSettings设置:
{ "AppSettings": { "token": "1234" } }
我已经在网上search如何从config.json读取AppSettings的值,但我没有得到任何有用的东西。
我试过了:
var configuration = new Configuration(); var appSettings = configuration.Get("AppSettings"); // null var token = configuration.Get("token"); // null
我知道与ASP.NET 4.0,你可以这样做:
System.Configuration.ConfigurationManager.AppSettings["token"];
但是,如何在ASP.NET Core中执行此操作?
这有几个曲折。 我已经修改了这个答案,以便与ASP.NET Core 1.0保持同步(截至2016年9月15日)。
这主要取自官方文件 :
首先,我们将所需的依赖项添加到我们的project.json
文件中,该文件位于Microsoft.Extensions.Configuration.*
命名空间下:
{ "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" }, "Microsoft.AspNetCore.Mvc": "1.0.0", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", "Microsoft.Extensions.Configuration": "1.0.0", "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", "Microsoft.Extensions.Configuration.Json":"1.0.0", "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", }, ... }
要处理ASP.NET应用程序中的设置,build议您只在应用程序的Startup
类中实例化一个Configuration
。 然后,使用“选项”模式访问各个设置。 假设我们有一个appsettings.json
文件,如下所示:
{ "ApplicationName": "MyApp", "Version": "1.0.0" }
我们有一个代表configuration的POCO对象:
public class MyConfig { public string ApplicationName { get; set; } public int Version { get; set; } }
现在我们在Startup.cs
构buildconfiguration:
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(); } }
如果我们想把我们的configuration注入到控制器中,我们需要在运行时注册它。 我们通过Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Add functionality to inject IOptions<T> services.AddOptions(); // Add our Config object so it can be injected services.Configure<MyConfig>(Configuration); }
我们像这样注入它:
public class HomeController : Controller { private readonly IOptions<MyConfig> config; public HomeController(IOptions<MyConfig> config) { this.config = config; } // GET: /<controller>/ public IActionResult Index() => View(config.Value); }
完整的Startup
类:
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(); } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Add functionality to inject IOptions<T> services.AddOptions(); // Add our Config object so it can be injected services.Configure<MyConfig>(Configuration); } }
首先:Microsoft.Framework.ConfigurationModel的程序集名称和命名空间已经更改为Microsoft.Framework.Configuration。 所以你应该使用:例如
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
作为project.json
的依赖项。 如果您没有安装7,请使用beta5或6。 那么你可以在Startup.cs
做这样的事情。
public IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = configurationBuilder.Build(); }
如果你想从config.json中获取一个variables,你可以马上使用:
public void Configure(IApplicationBuilder app) { // Add .Value to get the token string var token = Configuration.GetSection("AppSettings:token"); app.Run(async (context) => { await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value); }); }
或者你可以像这样创build一个名为AppSettings的类:
public class AppSettings { public string token { get; set; } }
并configuration这样的服务:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.Configure<MvcOptions>(options => { //mvc options }); services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); }
然后通过像这样的控制器访问它:
public class HomeController : Controller { private string _token; public HomeController(IOptions<AppSettings> settings) { _token = settings.Options.token; } }
他们只是不停地改变一些事情 – 刚刚更新了VS,并且让整个项目发生了轰炸,走上了恢复的道路,而新的方式如下所示:
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); }
我一直想念这一行!
.SetBasePath(env.ContentRootPath)
如果你只是想获得令牌的价值,然后使用
Configuration["AppSettings:token"]
对于.NET Core 2.0,情况有所改变。 启动构造函数将Configuration对象作为参数,因此不需要使用ConfigurationBuilder
。 这是我的:
public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig")); }
我的POCO是StorageOptions
提到的StorageOptions
对象:
namespace Brazzers.Models { public class StorageOptions { public String StorageConnectionString { get; set; } public String AccountName { get; set; } public String AccountKey { get; set; } public String DefaultEndpointsProtocol { get; set; } public String EndpointSuffix { get; set; } public StorageOptions() { } } }
而configuration实际上是我的appsettings.json
文件的一个子部分,命名为AzureStorageConfig
:
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;", "StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "AzureStorageConfig": { "AccountName": "brazzerswebapp", "AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==", "DefaultEndpointsProtocol": "https", "EndpointSuffix": "core.windows.net", "StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net" } }
我唯一要补充的是,由于构造函数已经改变,我还没有testing是否需要额外的加载appsettings.<environmentname>.json
appsettings.json
而不是appsettings.json
。