不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。Json在我的。net核心应用程序。我有我的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总是空的。我是不是遗漏了什么?
再加上David Liang对Core 2.0的回答——
appsettings。json文件链接到ASPNETCORE_ENVIRONMENT变量。
ASPNETCORE_ENVIRONMENT可以设置为任何值,但是框架支持三个值:Development、Staging和Production。如果没有设置ASPNETCORE_ENVIRONMENT,它将默认为Production。
对于这三个值,这些appsettings.ASPNETCORE_ENVIRONMENT。json文件支持开箱即用- appsettings.Staging。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; }
}
ASP。NET Core 3.1你可以遵循以下指南:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
当您创建一个新的ASP。在Program.cs中,你会有如下的配置行:
Host.CreateDefaultBuilder(args)
这将启用以下功能:
ChainedConfigurationProvider : Adds an existing IConfiguration as a
source. In the default configuration case, adds the host
configuration and setting it as the first source for the app
configuration.
appsettings.json using the JSON configuration
provider.
appsettings.Environment.json using the JSON configuration
provider. For example, appsettings.Production.json and
appsettings.Development.json.
App secrets when the app runs in the
Development environment.
Environment variables using the Environment
Variables configuration provider.
Command-line arguments using the
Command-line configuration provider.
这意味着您可以注入IConfiguration并使用字符串键获取值,甚至是嵌套值。像IConfiguration“父母:孩子”;
例子:
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();
}
}
只需创建一个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"];
假设在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();
方法二:依赖注入(推荐)
在Startup.cs文件:
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
...
services.AddServices(Configuration);
}
在你的控制器中:
public class TestController : ControllerBase
{
private string myValue1 { get; set; }
public TestController(IConfiguration configuration)
{
this.myValue1 = configuration.GetValue<string>("MyValues:Value1");
}
}
在我的例子中,它就像在Configuration对象上使用Bind()方法一样简单。然后将对象作为单例添加到DI中。
var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);
Instruction对象可以非常复杂。
{
"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"
}
}