不确定我在这里缺少什么,但我无法从我的.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<AppSettings>(_configuration.GetSection("AppSettings"));
}
}
型号:
public class AppSettings
{
public string Version{ get; set; }
}
控制器:
public class HomeController : Controller
{
private readonly AppSettings _mySettings;
public HomeController(IOptions<AppSettings> settings)
{
//This is always null
_mySettings = settings.Value;
}
}
_mySettings
始终为空。我在这里找不到什么东西吗?
答案 0 :(得分:99)
您不需要IConfiguration
构造函数中的新Startup
。其实施将由DI系统注入。
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
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<T>(this IConfiguration configuration);
public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
IConfiguration config) where TOptions : class;
我将使用Microsoft.AspNetCore.Identity
的所有安全相关服务放入其自己的名为DL.SO.Services.Security
的项目中。
appsettings.json中的安全设置
我定义了名为&#34; AppIdentitySettings&#34;的配置,用于我想在我的网络/启动项目的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
与Web项目的Startup
中的配置类之间配置绑定。但我更喜欢在单独的项目中定义扩展方法,以便您可以即插即用。
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<AppIdentitySettings>();
// Inject AppIdentitySettings so that others can use too
services.Configure<AppIdentitySettings>(settingsSection);
services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(connectionString, optionsBuilder =>
optionsBuilder.MigrationsAssembly(assemblyNamespace)
)
);
services.AddIdentity<AppUser, AppRole>(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<AppIdentityDbContext>()
.AddDefaultTokenProviders();
}
}
}
插入主要启动
namespace DL.SO.Web.UI
{
...
public void ConfigureServices(IServiceCollection services)
{
// Configure ASP.NET Core Identity
services.AddIdentitySecurityService(this.Configuration);
...
}
}
您需要告诉Startup
加载appsettings文件。
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
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指出来了!
答案 1 :(得分:35)
添加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; }
}
答案 2 :(得分:29)
只需创建一个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"
}
现在您可以使用它了。
不要忘记在班级中添加引用。
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"];
答案 3 :(得分:20)
我猜最简单的方法是通过DI。进入Controller的示例。
SAMPLE_TIME = 100
SAMPLE_RATE = 0.2
x = np.arange(0, SAMPLE_TIME, SAMPLE_RATE)
deflection = 20
damping_coefficent = 0.1
w = 2*np.pi
el = deflection * np.exp(-x*damping_coefficent) * np.cos(w * x)
plt.plot(x, el)
plt.xlabel('x')
plt.ylabel('$f(x)$')
答案 4 :(得分:5)
在Startup类的构造函数中,您可以使用注入的IConfiguration对象访问appsettings.json和许多其他设置:
Startup.cs构造函数
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//here you go
var myvalue = Configuration["Grandfather:Father:Child"];
}
public IConfiguration Configuration { get; }
appsettings.json
的内容 {
"Grandfather": {
"Father": {
"Child": "myvalue"
}
}
答案 5 :(得分:2)
public static void GetSection()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];
}
答案 6 :(得分:2)
对于ASP.NET Core 3.1,您可以遵循此指南:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
在创建新的ASP.NET Core 3.1项目时,您将在Program.cs
中具有以下配置行:
Host.CreateDefaultBuilder(args)
这将启用以下功能:
这意味着您可以注入IConfiguration
并使用字符串键获取值,甚至是嵌套值。像IConfiguration["Parent:Child"];
示例:
appsettings.json
{
"ApplicationInsights":
{
"Instrumentationkey":"putrealikeyhere"
}
}
WeatherForecast.cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var key = _configuration["ApplicationInsights:InstrumentationKey"];
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
答案 7 :(得分:1)
从Asp.net core 2.2或更高版本开始,您可以编写以下代码:
步骤1。创建一个AppSettings类文件。
此文件包含一些方法,可帮助您从appsettings.json文件中通过密钥获取价值。如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ReadConfig.Bsl
{
public class AppSettings
{
private static AppSettings _instance;
private static readonly object ObjLocked = new object();
private IConfiguration _configuration;
protected AppSettings()
{
}
public void SetConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
public static AppSettings Instance
{
get
{
if (null == _instance)
{
lock (ObjLocked)
{
if (null == _instance)
_instance = new AppSettings();
}
}
return _instance;
}
}
public string GetConnection(string key, string defaultValue = "")
{
try
{
return _configuration.GetConnectionString(key);
}
catch
{
return defaultValue;
}
}
public T Get<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
public T Get<T>(string key, T defaultValue)
{
if (_configuration.GetSection(key) == null)
return defaultValue;
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
public static T GetObject<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return Instance._configuration.Get<T>();
else
{
var section = Instance._configuration.GetSection(key);
return section.Get<T>();
}
}
public static T GetObject<T>(string key, T defaultValue)
{
if (Instance._configuration.GetSection(key) == null)
return defaultValue;
if (string.IsNullOrWhiteSpace(key))
return Instance._configuration.Get<T>();
else
return Instance._configuration.GetSection(key).Get<T>();
}
}
}
第2步。AppSettings对象的初始配置
我们需要在应用程序启动时声明并加载appsettings.json文件,并加载AppSettings对象的配置信息。我们将在Startup.cs文件的构造函数中完成此工作。
请注意第AppSettings.Instance.SetConfiguration(Configuration);
行
public Startup(IHostingEnvironment evm)
{
var builder = new ConfigurationBuilder()
.SetBasePath(evm.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build(); // load all file config to Configuration property
AppSettings.Instance.SetConfiguration(Configuration);
}
好的,现在我有一个appsettings.json文件,其中包含一些键,如下所示:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "Data Source=localhost;Initial Catalog=ReadConfig;Persist Security Info=True;User ID=sa;Password=12345;"
},
"MailConfig": {
"Servers": {
"MailGun": {
"Pass": "65-1B-C9-B9-27-00",
"Port": "587",
"Host": "smtp.gmail.com"
}
},
"Sender": {
"Email": "example@gmail.com",
"Pass": "123456"
}
}
}
第3步。从操作中读取配置值
我使演示程序在Home控制器中执行以下操作:
public class HomeController : Controller
{
public IActionResult Index()
{
var connectionString = AppSettings.Instance.GetConnection("ConnectionString");
var emailSender = AppSettings.Instance.Get<string>("MailConfig:Sender:Email");
var emailHost = AppSettings.Instance.Get<string>("MailConfig:Servers:MailGun:Host");
string returnText = " 1. Connection String \n";
returnText += " " +connectionString;
returnText += "\n 2. Email info";
returnText += "\n Sender : " + emailSender;
returnText += "\n Host : " + emailHost;
return Content(returnText);
}
}
结果如下:
有关更多信息,请参阅asp.net核心中的文章get value from appsettings.json,以获取更多详细代码。
答案 8 :(得分:0)
就我而言,这很简单,就像在Configuration对象上使用Bind()方法一样。然后在DI中将对象添加为单例。
var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);
指令对象可以任意复杂。
{
"InstructionSettings": {
"Header": "uat_TEST",
"SVSCode": "FICA",
"CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
"Username": "s_integrat",
"Password": "X@nkmail6",
"Defaults": {
"Language": "ENG",
"ContactDetails":{
"StreetNumber": "9",
"StreetName": "Nano Drive",
"City": "Johannesburg",
"Suburb": "Sandton",
"Province": "Gauteng",
"PostCode": "2196",
"Email": "ourDefaultEmail@companyName.co.za",
"CellNumber": "0833 468 378",
"HomeNumber": "0833 468 378",
}
"CountryOfBirth": "710"
}
}
答案 9 :(得分:0)
我认为最好的选择是:
创建一个模型类作为配置模式
在DI中注册: services.Configure(Configuration.GetSection(“ democonfig”));
从控制器中的DI获取值作为模型对象:
[f'/Users/emadboctor/Desktop/images/{image}' for image os.listdir('../images')]
答案 10 :(得分:0)
很简单: 在appsettings.json
"MyValues": {
"Value1": "Xyz"
}
在.cs文件中:
static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
public static string myValue1= conf["MyValues:Value1"].ToString();
答案 11 :(得分:0)
.NET core 3.X
无需创建新模型并在Startup.cs中进行设置。
控制器 添加新程序包-使用Microsoft.Extensions.Configuration;
public class HomeController : Controller
{
private readonly IConfiguration _mySettings;
public HomeController (IConfiguration mySettings)
{
_mySettings= mySettings;
}
//ex: you can get value on below function
public IEnumerable<string> Get()
{
var result = _config.GetValue<string>("AppSettings:Version"); // "One"
return new string[] { result.ToString() };
}
}
答案 12 :(得分:0)
在startup.cs中,添加构造函数
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
使用 Configuration["SecureCookies"] 访问设置
答案 13 :(得分:0)
这往往发生在 vscode 上,正如我所假设的那样,因为人们如何配置 launch.json
。
基于 this answer,我不得不重新配置正在搜索的配置的基本路径为 DLL's path,并且由于默认设置是可选的,因此很难在 .net 上进行跟踪核心 3.1 和网络 5.0 应用程序。这是我重新配置的方式
Program.cs
:
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace API
{
public class Program
{
public static int Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
return 0;
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(c =>
{
var codeBase = Assembly.GetExecutingAssembly().Location;
var uri = new UriBuilder(codeBase);
var path = Uri.UnescapeDataString(uri.Path);
var assembyDirectory = Path.GetDirectoryName(path);
c.SetBasePath(assembyDirectory);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
;
}
}
}
我可以在 Startup.cs
中正常访问配置:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model;
namespace API
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var myOptions = Configuration.To<ApiConfig>();
services.AddAuthentication(myOptions.Secret);
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}
答案 14 :(得分:0)
我发现使用 .NET Core 3+ 执行以下操作最容易。我发现使用 HostBuilders 等的所有其他方法都有些冗长且不那么可读。这不是专门针对 ASP.Net 但您可以对其进行调整...
创建json:
{
"GlobalConfig": {
"BlacklistedPairs": [ "USD", "USDT", "BUSD", "TUSD", "USDC", "DAI", "USDK" ]
},
"CoinTrackingConfig": {
"Cookie1": "",
"Cookie2": "",
"ApiKey": "",
"ApiSecret": "",
"UpdateJobs": [
{
"Name": "Binance",
"Path": "binance_api",
"JobId": 42202
},
{
"Name": "Bitfinex",
"Path": "bitfinex_api",
"JobId": 9708
}
]
},
"DiscordConfig": {
"BotToken": ""
}
}
为 json 对象创建类:
class GlobalConfig
{
public string[] BlacklistedPairs { get; set; }
}
class CoinTrackingConfig
{
public string Cookie1 { get; set; }
public string Cookie2 { get; set; }
public string ApiKey { get; set; }
public string ApiSecret { get; set; }
public List<CoinTrackingUpdateJobs> UpdateJobs { get; set; }
}
class CoinTrackingUpdateJobs
{
public string Name { get; set; }
public string Path { get; set; }
public int JobId { get; set; }
}
class DiscordConfig
{
public string BotToken { get; set; }
}
创建一个辅助类:
private class Config
{
private IConfigurationRoot _configuration;
public Config(string config) => _configuration = new ConfigurationBuilder()
.AddJsonFile(config)
.Build();
public T Get<T>() where T : new()
{
var obj = new T();
_configuration.GetSection(typeof(T).Name).Bind(obj);
return obj;
}
}
服务提供者选项和服务构造函数:
public class DiscordServiceOptions
{
public string BotToken { get; set; }
}
public DiscordService(IOptions<DiscordServiceOptions> options, ILogger<DiscordService> logger)
{
_logger = logger;
_client = new DiscordSocketClient();
_client.Log += Log;
_client.Ready += OnReady;
_client.Disconnected += OnDisconnected;
_client.LoginAsync(TokenType.Bot, options.Value.BotToken);
_client.StartAsync();
}
像这样初始化(将配置传递给服务提供者 - IOptions 将在构建服务时传入):
static async Task Main(string[] args)
{
var _config = new Config("config.json");
var globalConfig = config.Get<GlobalConfig>();
var coinTrackingConfig = config.Get<CoinTrackingConfig>();
var discordConfig = config.Get<DiscordConfig>();
_services = new ServiceCollection()
.AddOptions()
.Configure<DiscordServiceOptions>(options =>
{
options.BotToken = discordConfig.BotToken;
})
.AddSingleton<IDiscordService, DiscordService>()
.AddLogging(logging =>
{
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddNLog(new NLogProviderOptions
{
CaptureMessageTemplates = true,
CaptureMessageProperties = true
});
})
.BuildServiceProvider();
}