从.net核心中的appsettings.json获取价值
不知道我在这里缺少什么,但我无法从我的.net核心应用程序中的appsettings.json获取值。 我的appsettings.json为:
{ "AppSettings": { "Version": "One" } }
启动:
public class Startup { private IConfigurationRoot _configuration; public Startup(IHostingEnvironment env) { _configuration = new ConfigurationBuilder() } public void ConfigureServices(IServiceCollection services) { //Here I setup to read appsettings services.Configure(_configuration.GetSection("AppSettings")); } }
模型:
public class AppSettings { public string Version{ get; set; } }
控制器:
public class HomeController : Controller { private readonly AppSettings _mySettings; public HomeController(IOptions settings) { //This is always null _mySettings = settings.Value; } }
_mySettings
始终为null。 这里有什么我想念的吗?
核心2.0
您不需要在Startup
构造函数中使用新的IConfiguration
。 其实施将由DI系统注入。
Program.cs中
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() .Build(); }
Startup.cs
public class Startup { public IHostingEnvironment HostingEnvironment { get; private set; } public IConfiguration Configuration { get; private set; } public Startup(IConfiguration configuration, IHostingEnvironment env) { this.HostingEnvironment = env; this.Configuration = configuration; } }
奖金:
如果使用类库将解决方案分成多个项目, Microsoft.Extensions.Options.ConfigurationExtensions包可以方便地读取appsettings
文件中的值并将它们注入到项目中的配置类中。
它有2个扩展你可以使用:
public static T Get(this IConfiguration configuration); public static IServiceCollection Configure(this IServiceCollection services, IConfiguration config) where TOptions : class;
例:
我将所有与安全相关的服务使用Microsoft.AspNetCore.Identity
放入其自己的名为DL.SO.Services.Security
的项目中。
appsettings.json中的安全设置
我定义了名为“AppIdentitySettings”的配置,用于我想在我的web / start-up项目中的ASP.NET Core Identity
框架中设置的身份选项。
{ "ConnectionStrings": { ... }, "AppIdentitySettings": { "User": { "RequireUniqueEmail": true }, "Password": { "RequiredLength": 6, "RequireLowercase": true, "RequireUppercase": true, "RequireDigit": true, "RequireNonAlphanumeric": true }, "Lockout": { "AllowedForNewUsers": true, "DefaultLockoutTimeSpanInMins": 30, "MaxFailedAccessAttempts": 5 } }, "Recaptcha": { ... }, ... }
配置类
然后,您需要定义配置类,它们只是POCO,用于表示appsettings.json中的配置结构。 配置类的名称不必与您在appsettings.json
定义的部分名称匹配,而是需要匹配的属性名称。
namespace DL.SO.Services.Security { public class AppIdentitySettings { public UserSettings User { get; set; } public PasswordSettings Password { get; set; } public LockoutSettings Lockout { get; set; } } public class UserSettings { public bool RequireUniqueEmail { get; set; } } public class PasswordSettings { public int RequiredLength { get; set; } public bool RequireLowercase { get; set; } public bool RequireUppercase { get; set; } public bool RequireDigit { get; set; } public bool RequireNonAlphanumeric { get; set; } } public class LockoutSettings { public bool AllowedForNewUsers { get; set; } public int DefaultLockoutTimeSpanInMins { get; set; } public int MaxFailedAccessAttempts { get; set; } } }
扩展方法
您可以在appsettings.json
项目的Startup
中配置appsettings.json
与这些配置类之间的绑定。 但我更喜欢在单独的项目中定义扩展方法,以便您可以即插即用。
using DL.SO.Services.Security.Entities; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace DL.SO.Services.Security.Extensions { public static class ServiceCollectionExtensions { public static void AddIdentitySecurityService(this IServiceCollection services, IConfiguration configuration) { string connectionString = configuration.GetConnectionString("AppDbConnection"); string assemblyNamespace = typeof(AppIdentityDbContext).Namespace; var settingsSection = configuration.GetSection("AppIdentitySettings"); var settings = settingsSection.Get(); // Inject AppIdentitySettings so that others can use too services.Configure (settingsSection); services.AddDbContext(options => options.UseSqlServer(connectionString, optionsBuilder => optionsBuilder.MigrationsAssembly(assemblyNamespace) ) ); services.AddIdentity(options => { // User settings options.User.RequireUniqueEmail = settings.User.RequireUniqueEmail; // Password settings options.Password.RequireDigit = settings.Password.RequireDigit; options.Password.RequiredLength = settings.Password.RequiredLength; options.Password.RequireLowercase = settings.Password.RequireLowercase; options.Password.RequireNonAlphanumeric = settings.Password.RequireNonAlphanumeric; options.Password.RequireUppercase = settings.Password.RequireUppercase; // Lockout settings options.Lockout.AllowedForNewUsers = settings.Lockout.AllowedForNewUsers; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(settings.Lockout.DefaultLockoutTimeSpanInMins); options.Lockout.MaxFailedAccessAttempts = settings.Lockout.MaxFailedAccessAttempts; }) .AddEntityFrameworkStores () .AddDefaultTokenProviders(); } } }
插入主要启动
namespace DL.SO.Web.UI { ... public void ConfigureServices(IServiceCollection services) { // Configure ASP.NET Core Identity services.AddIdentitySecurityService(this.Configuration); ... } }
核心1.x
您需要告诉Startup
加载appsettings文件。
Program.cs中
public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup() .UseApplicationInsights() .Build(); host.Run(); } }
Startup.cs
public class Startup { public IConfigurationRoot Configuration { get; private set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); this.Configuration = builder.Build(); } ... }
谢谢@Kirk指出来了!
添加David Liang对Core 2.0的回答 –
appsettings.json
文件链接到ASPNETCORE_ENVIRONMENT
变量。
ASPNETCORE_ENVIRONMENT
可以设置为任何值,但框架支持三个值: Development
, Staging
和Production
。 如果未设置ASPNETCORE_ENVIRONMENT
,则默认为Production
。
对于这三个值,这些appsettings.ASPNETCORE_ENVIRONMENT.json文件支持开箱即用 – appsettings.Staging.json
, appsettings.Development.json
和appsettings.Production.json
以上三个应用程序设置json文件可用于配置多个环境。
示例 – appsettings.Staging.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "System": "Information", "Microsoft": "Information" } }, "MyConfig": "My Config Value for staging." }
使用Configuration["config_var"]
检索任何配置值。
public class Startup { public Startup(IHostingEnvironment env, IConfiguration config) { Environment = env; Configuration = config; var myconfig = Configuration["MyConfig"]; } public IConfiguration Configuration { get; } public IHostingEnvironment Environment { get; } }
只需创建一个AnyName.cs文件并粘贴以下代码即可。
using System; using System.IO; using Microsoft.Extensions.Configuration; namespace Custom { static class ConfigurationManager { public static IConfiguration AppSetting { get; } static ConfigurationManager() { AppSetting = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("YouAppSettingFile.json") .Build(); } } }
必须用您的文件名替换YouAppSettingFile.json文件名。
您的.json文件应如下所示。
{ "GrandParent_Key" : { "Parent_Key" : { "Child_Key" : "value1" } }, "Parent_Key" : { "Child_Key" : "value2" }, "Child_Key" : "value3" }
现在你可以使用它了。
不要忘记在您要使用的class级中添加参考 。
using Custom;
用于检索值的代码。
string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"]; string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"]; string value3 = ConfigurationManager.AppSetting["Child_Key"];
我想最简单的方法是DI。 进入Controller的一个例子。
// StartUp.cs public void ConfigureServices(IServiceCollection services) { ... // for get appsettings from anywhere services.AddSingleton(Configuration); } public class ContactUsController : Controller { readonly IConfiguration _configuration; public ContactUsController( IConfiguration configuration) { _configuration = configuration; // sample: var apiKey = _configuration.GetValue("SendGrid:CAAO"); ... } }