我在appsettings / Config .json中设置了我的AppSettings数据,如下所示:
{
"AppSettings": {
"token": "1234"
}
}
我在网上搜索过如何从.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中执行此操作?
答案 0 :(得分:203)
这有一些曲折。我已将此答案修改为 ASP.NET Core 2.0 (截至26/02/2018)。
这主要来自the official documentation:
要在ASP.NET应用程序中使用设置,建议您仅在应用程序的Configuration
类中实例化Startup
。然后,使用“选项”模式访问各个设置。假设我们有一个appsettings.json
文件,如下所示:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
我们有一个代表配置的POCO对象:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
现在我们在Startup.cs
:
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();
}
}
请注意,{Core} 2.0中appsettings.json
默认 。如果需要,我们还可以为每个环境注册一个appsettings.{Environment}.json
配置文件。
如果我们想将配置注入控制器,我们需要在运行时注册它。我们是通过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.GetSection("MyConfig"));
}
我们这样注入:
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.GetSection("MyConfig"));
}
}
答案 1 :(得分:51)
首先: Microsoft.Framework.ConfigurationModel的程序集名称和命名空间已更改为Microsoft.Framework.Configuration。所以你应该使用: e.g。
"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中检索变量,可以使用以下命令立即获取:
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);
});
}
或者您可以创建一个名为AppSettings的类:
public class AppSettings
{
public string token { get; set; }
}
并配置如下服务:
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;
}
}
答案 2 :(得分:33)
对于.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
对象:
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() { }
}
}
配置实际上是我的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"
}
}
我唯一要补充的是,由于构造函数已经更改,我还没有测试是否需要为加载appsettings.<environmentname>.json
而不是appsettings.json
加载额外的东西。< / p>
答案 3 :(得分:15)
如果您只想获取令牌的值,请使用
Configuration["AppSettings:token"]
答案 4 :(得分:9)
对于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();
}
}
答案 5 :(得分:9)
以下适用于控制台应用程序;
1-安装以下nuget
个软件包(.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
2-在根级别创建appsettings.json
。右键单击它,然后将其“复制到输出目录”复制为“ 如果更新则复制”。
3-示例配置文件:
{
"AppConfig": {
"FilePath": "C:\\temp\\logs\\output.txt"
}
}
4- Program.cs
configurationSection.Key
和configurationSection.Value
将具有配置属性。
static void Main(string[] args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\\temp\\logs\\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
答案 6 :(得分:6)
只是为了补充Yuval Itzchakov的答案。
您可以在不使用构建器功能的情况下加载配置,只需注入它即可。
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
答案 7 :(得分:6)
对于.NET Core 2.0,您只需:
在appsettings.json中声明您的键/值对:
{
"MyKey": "MyValue"
}
将配置服务注入startup.cs,并使用该服务获取值
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
答案 8 :(得分:5)
除了现有的答案外,我还想提一下,为简单起见,有时为IConfiguration
使用扩展方法可能会有用。
我将JWT配置保留在appsettings.json中,因此我的扩展方法类如下所示:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string[] GetCorsOrigins(this IConfiguration configuration)
{
string[] result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
它节省了很多行,而您只编写了简洁的代码:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
也可以将IConfiguration
实例注册为单例并将其注入到您需要的任何地方-我使用Autofac容器,方法如下:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
您可以对MS Dependency Injection做同样的事情:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
答案 9 :(得分:4)
这对我有用.Net Core 5
我有一个 appsettings.development.json 文件。我选择了“开发”环境,这就是我在 development.json 文件中设置的原因。您可以在默认环境下使用 appsettings.josn。
使用此配置
创建一个具有配置属性的类
在 Startup 中注册我的电话
我现在可以在我的控制器中访问
答案 10 :(得分:4)
使用Core 2.2,并且以最简单的方式...
public IActionResult Index([FromServices] IConfiguration config)
{
var myValue = config.GetValue<string>("MyKey");
}
appsettings.json
会通过构造函数或动作注入自动加载并可用,并且GetSection
上还有一个IConfiguration
方法。如果您只需要Startup.cs
,则无需更改Program.cs
或appsettings.json
。
答案 11 :(得分:3)
.NET Core 3.0 可能不是从 appsettings.json 获取值的最佳方法,但这很简单,并且可以在我的应用程序中使用!
public function edit(Request $request)
{
//
$id= $request->id;
$tkt= $request->tkt_id;
}
顶部:
{
"ConnectionStrings": {
"DefaultConnection":****;"
}
"AppSettings": {
"APP_Name": "MT_Service",
"APP_Version": "1.0.0"
}
}
在您的代码中:
using Microsoft.Extensions.Configuration;
答案 12 :(得分:3)
他们只是不断改变事情 - 刚刚更新了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)
答案 13 :(得分:2)
您可以尝试以下代码。 这对我有用。
public class Settings
{
private static IHttpContextAccessor _HttpContextAccessor;
public Settings(IHttpContextAccessor httpContextAccessor)
{
_HttpContextAccessor = httpContextAccessor;
}
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_HttpContextAccessor = httpContextAccessor;
}
public static IConfigurationBuilder Getbuilder()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
return builder;
}
public static string GetAppSetting(string key)
{
//return Convert.ToString(ConfigurationManager.AppSettings[key]);
var builder = Getbuilder();
var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
return GetAppStringData;
}
public static string GetConnectionString(string key="DefaultName")
{
var builder = Getbuilder();
var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
return ConnectionString;
}
}
在这里我创建了一个类来获取连接字符串和应用程序设置。
我需要注册Startup.cs文件,如下所示。
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
Settings.Configure(httpContextAccessor);
}
}
答案 14 :(得分:2)
.NET Core 2.1.0
var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = builder.Build();
3。安装以下依赖项:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.json
4。然后,重要提示: 右键单击appsettings.json文件->单击属性->选择复制(如果较新):
最后,您可以这样做:
config [“ key1”]
考虑到我的配置文件如下:
{ "ConnectionStrings": "myconnection string here", "key1": "value here" }
答案 15 :(得分:2)
.NET Core 2.2方式
(毫无疑问,Microsoft将在下一个.NET版本中再次将其更改为完全不同的内容。)
它可能看起来像这样。在这里,我们将加载Setting1和Setting2
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Setting1": "abc",
"Setting2": 123
}
用于保存Setting1和Setting2的POCO类。我们将把appsettings.json加载到该类对象中。 POCO类的结构应与JSON文件匹配,如果需要,属性可以嵌套在其他属性/类中。
public class AppSettings
{
public string Setting1 { get; set; }
public int Setting2 { get; set; }
}
将appSettings.json加载到您的AppSettings对象中并开始使用它:
public class Startup
{
public Startup(IConfiguration configuration)
{
AppSettings settings = new AppSettings();
Configuration = configuration;
configuration.Bind(settings);
// Now start using it
string setting1 = settings.Setting1;
int setting2 = settings.Setting2;
}
答案 16 :(得分:2)
我怀疑这是好习惯,但它在本地工作。如果我在发布/部署(到IIS Web服务)时失败,我会更新它。
步骤1 - 将此程序集添加到类的顶部(在我的示例中为控制器类):
using Microsoft.Extensions.Configuration;
第2步 - 添加此类似内容:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
步骤3 - 通过执行此操作调用键的值(返回字符串):
config["NameOfYourKey"]
答案 17 :(得分:1)
这是“欺骗”吗?我只是将“启动”类中的“配置”设为静态,然后可以从其他任何地方访问它:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
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)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
答案 18 :(得分:1)
首先应注入IConfiguration,然后从appsettings中读取,可以使用以下方法之一:
1:获取路段数据
var redisConfig = configuration.GetSection("RedisConfig");
2:在一个部分中获取一个值
var redisServer = configuration.GetValue<string>("RedisConfig:ServerName");
3:在部分中获取嵌套值
var redisExpireMInutes = configuration.GetValue<int>("RedisConfig:ServerName:ExpireMInutes");
答案 19 :(得分:1)
超级晚会,但是如果有人发现了。
您可以从Microsoft.Extensions.Configuration调用IConfiguration;
public static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();
答案 20 :(得分:0)
这是ASP.NET Core的完整用例!
articles.json
{
"shownArticlesCount": 3,
"articles": [
{
"title": "My Title 1",
"thumbnailLink": "example.com/img1.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
{
"title": "My Title 2",
"thumbnailLink": "example.com/img2.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
]
}
ArticleContainer.cs
public class ArticleContainer
{
public int ShownArticlesCount { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public string Title { get; set; }
public string ThumbnailLink { get; set; }
public string AuthorName { get; set; }
public string AuthorProfileLink { get; set; }
public DateTime PublishDate { get; set; }
public string Text { get; set; }
public string Link { get; set; }
}
Startup.cs
public class Startup
{
public IConfigurationRoot ArticleConfiguration { get; set; }
public Startup(IHostingEnvironment env)
{
ArticleConfiguration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("articles.json")
.Build();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<ArticleContainer>(ArticleConfiguration);
}
}
Index.cshtml.cs
public class IndexModel : PageModel
{
public ArticleContainer ArticleContainer { get;set; }
private readonly IOptions<ArticleContainer> _articleContainer;
public IndexModel(IOptions<ArticleContainer> articleContainer)
{
_articleContainer = articleContainer;
}
public void OnGet()
{
ArticleContainer = _articleContainer.Value;
}
}
Index.cshtml.cs
<h1>@Model.ArticleContainer.ShownArticlesCount</h1>
答案 21 :(得分:0)
通过调用Get<YourType>()
将其作为对象放入控制器内部
public IActionResult Index([FromServices] IConfiguration config)
{
BillModel model= config.GetSection("Yst.Requisites").Get<BillModel>();
return View(model);
}
答案 22 :(得分:0)
使用netcoreapp 3.1的最新版本,您可以非常简单地进行此操作,而无需任何第三方依赖性。
我created a gist for this,但是您可以使用此类读取JSON文件并返回动态属性。
using System.Text.Json;
using System.IO;
class ConfigurationLoader
{
private dynamic configJsonData;
public ConfigurationLoader Load(string configFilePath = "appsettings.json")
{
var appSettings = File.ReadAllText(configFilePath);
this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
return this;
}
public dynamic GetProperty(string key)
{
var properties = key.Split(".");
dynamic property = this.configJsonData;
foreach (var prop in properties)
{
property = property.GetProperty(prop);
}
return property;
}
}
我专门做了这个,所以我可以在我的dotnet控制台应用程序中使用appconfig.json。我只是将其放在我的Program.Main
函数中:
var config = new ConfigurationLoader();
config.Load();
Console.WriteLine(config.GetProperty("Environment.Name"));
这将返回该属性的dynamic
对象。 (如果不是基本类型,则为JsonElement)。
我的appsettings.json
文件如下所示:
{
"Environment": {
"Token": "abc-123",
"Name": "Production"
}
}