本文整理汇总了C#中Microsoft.Extensions.Configuration.ConfigurationBuilder.AddJsonFile方法的典型用法代码示例。如果您正苦于以下问题:C# ConfigurationBuilder.AddJsonFile方法的具体用法?C# ConfigurationBuilder.AddJsonFile怎么用?C# ConfigurationBuilder.AddJsonFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Extensions.Configuration.ConfigurationBuilder
的用法示例。
在下文中一共展示了ConfigurationBuilder.AddJsonFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetEnabledTenants
//<inheritdoc/>
public IEnumerable<Tenant> GetEnabledTenants()
{
var fileProvider = _hostingEnvironment.ContentRootFileProvider;
var tenantFolders = fileProvider
.GetDirectoryContents("tenants")
.Where(info => info.IsDirectory);
foreach (var tenantFolder in tenantFolders)
{
var tenantFileName = "tenant.json";
var tenantDirectoryPath = Path.Combine("tenants", tenantFolder.Name);
var tenantFilePath = Path.Combine(tenantDirectoryPath, tenantFileName);
var tenantFileInfo = fileProvider.GetFileInfo(tenantFilePath);
if (tenantFileInfo.Exists)
{
var builder = new ConfigurationBuilder();
builder.SetFileProvider(fileProvider);
builder.AddJsonFile(tenantFilePath);
var config = builder.Build();
var tenant = new Tenant
{
TenantId = tenantFolder.Name,
Configuration = config,
Identities = config.GetSection("Identities").GetChildren().Select(t => t.Value),
Extensions = config.GetSection("Extensions").GetChildren().Select(t => t.Value),
Path = tenantFolder.PhysicalPath
};
yield return tenant;
}
}
}
示例2: ConfigureConfiguration
/// <summary>
/// Creates and configures the application configuration, where key value pair settings are stored. See
/// http://docs.asp.net/en/latest/fundamentals/configuration.html
/// http://weblog.west-wind.com/posts/2015/Jun/03/Strongly-typed-AppSettings-Configuration-in-ASPNET-5
/// </summary>
/// <param name="hostingEnvironment">The environment the application is running under. This can be Development,
/// Staging or Production by default.</param>
/// <returns>A collection of key value pair settings.</returns>
private static IConfiguration ConfigureConfiguration(IHostingEnvironment hostingEnvironment)
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// Add configuration from the config.json file.
configurationBuilder.AddJsonFile("config.json");
// Add configuration from an optional config.development.json, config.staging.json or
// config.production.json file, depending on the environment. These settings override the ones in the
// config.json file.
configurationBuilder.AddJsonFile($"config.{hostingEnvironment.EnvironmentName}.json", optional: true);
// This reads the configuration keys from the secret store. This allows you to store connection strings
// and other sensitive settings, so you don't have to check them into your source control provider. See
// http://go.microsoft.com/fwlink/?LinkID=532709 and
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddUserSecrets();
// Add configuration specific to the Development, Staging or Production environments. This config can
// be stored on the machine being deployed to or if you are using Azure, in the cloud. These settings
// override the ones in all of the above config files.
// Note: To set environment variables for debugging navigate to:
// Project Properties -> Debug Tab -> Environment Variables
// Note: To get environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]
// Note: To set environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]="[VARIABLE_VALUE]"
// Note: Environment variables use a colon separator e.g. You can override the site title by creating a
// variable named AppSettings:SiteTitle. See
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddEnvironmentVariables();
return configurationBuilder.Build();
}
示例3: Startup
/// <summary>
/// 1. Loads configurations
/// </summary>
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder();
// general config file
builder.AddJsonFile("config.json");
// environment-specific config
builder.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
// sensitive information config
if (env.IsDevelopment()) builder.AddUserSecrets();
Configuration = builder.Build();
}
示例4: Functional
public Functional()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("config.json");
builder.AddJsonFile("config.private.json", true);
var configuration = builder.Build();
var uri = new Uri(configuration["ServerCredentialUri"]);
var username = configuration["ServerCredentialUsername"];
var password = configuration["ServerCredentialPassword"];
_serverCredential = new ServerCredential(uri, username, password);
}
示例5: BuildLightcoreConfiguration
public static IConfiguration BuildLightcoreConfiguration(this IApplicationEnvironment appEnv, IHostingEnvironment env)
{
var builder = new ConfigurationBuilder().SetBasePath(appEnv.ApplicationBasePath);
// Add main config file
builder.AddJsonFile("lightcore.json");
// Add optional environment specific config file, will be merged and duplicates takes precedence
builder.AddJsonFile($"lightcore.{env.EnvironmentName}.json", true);
// Add environment variables, will be merged and duplicates takes precedence - Set LightcoreConfig:ServerUrl in Azure for example...
builder.AddEnvironmentVariables();
return builder.Build();
}
示例6: Startup
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath);
if (env.IsDevelopment())
{
builder.AddJsonFile("config.json",true,true);
}
else
{
builder.AddJsonFile("/etc/bahamut/website.json",true,true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
示例7: Startup
public Startup()
{
var cb = new ConfigurationBuilder();
cb.AddJsonFile("appSettings.json");
_configuration = cb.Build();
}
示例8: HalibutLimits
static HalibutLimits()
{
#if NET40
var settings = System.Configuration.ConfigurationManager.AppSettings;
var fields = typeof (HalibutLimits).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (var field in fields)
{
var value = settings.Get("Halibut." + field.Name);
if (string.IsNullOrWhiteSpace(value)) continue;
var time = TimeSpan.Parse(value);
field.SetValue(null, time);
}
#else
// should be able to use Directory.GetCurrentDirectory()
// to get the working path, but the nunit test runner
// runs from another directory. Go with dll location for now.
var directory = Path.GetDirectoryName(new Uri(typeof(HalibutLimits).GetTypeInfo().Assembly.CodeBase).LocalPath);
var builder = new ConfigurationBuilder();
builder.SetBasePath(directory);
builder.AddJsonFile("appsettings.json", optional: true);
var halibutConfig = builder.Build();
var fields = typeof(HalibutLimits).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (var field in fields)
{
var value = halibutConfig["Halibut:" + field.Name];
if (string.IsNullOrWhiteSpace(value)) continue;
var time = TimeSpan.Parse(value);
field.SetValue(null, time);
}
#endif
}
示例9: SpringCloudConfigServer_ReturnsExpectedDefaultData
public void SpringCloudConfigServer_ReturnsExpectedDefaultData()
{
// Arrange
var appsettings = @"
{
'spring': {
'application': {
'name' : 'foo'
},
'cloud': {
'config': {
'uri': 'http://localhost:8888',
'env': 'development'
}
}
}
}";
var path = ConfigServerTestHelpers.CreateTempFile(appsettings);
var configurationBuilder = new ConfigurationBuilder();
var hostingEnv = new HostingEnvironment();
configurationBuilder.AddJsonFile(path);
// Act and Assert (expects Spring Cloud Config server to be running)
configurationBuilder.AddConfigServer(hostingEnv);
IConfigurationRoot root = configurationBuilder.Build();
Assert.Equal("spam", root["bar"]);
Assert.Equal("bar", root["foo"]);
Assert.Equal("Spring Cloud Samples", root["info:description"]);
Assert.Equal("https://github.com/spring-cloud-samples", root["info:url"]);
Assert.Equal("http://localhost:8761/eureka/", root["eureka:client:serviceUrl:defaultZone"]);
}
开发者ID:chrisumbel,项目名称:Configuration,代码行数:35,代码来源:ConfigServerConfigurationExtensionsIntegrationTest.cs
示例10: Startup
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
// this file name is ignored by gitignore
// so you can create it and use on your local dev machine
// remember last config source added wins if it has the same settings
builder.AddJsonFile("appsettings.local.overrides.json", optional: true);
// most common use of environment variables would be in azure hosting
// since it is added last anything in env vars would trump the same setting in previous config sources
// so no risk of messing up settings if deploying a new version to azure
builder.AddEnvironmentVariables();
Configuration = builder.Build();
//env.MapPath
appBasePath = appEnv.ApplicationBasePath;
}
示例11: Main
public void Main(string[] args)
{
Log("started with args: "+String.Join(" ", args));
var configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile("appsettings.json");
Configuration = configBuilder.Build();
if (args.Contains("--windows-service"))
{
try
{
Log("WWWService Main()");
Run(this);
return;
}
catch(Exception x)
{
Log("WWWService Main() Exception: "+ x.Message);
}
}
OnStart(null);
Console.ReadLine();
OnStop();
}
示例12: Main
public int Main(string[] args)
{
var builder = new ConfigurationBuilder();
//builder.Add(new JsonConfigurationSource("config.json"));
builder.AddJsonFile("config.json");
var config = builder.Build();
var webjobsConnectionString = config["Data:AzureWebJobsStorage:ConnectionString"];
var dbConnectionString = config["Data:DefaultConnection:ConnectionString"];
if (string.IsNullOrWhiteSpace(webjobsConnectionString))
{
Console.WriteLine("The configuration value for Azure Web Jobs Connection String is missing.");
return 10;
}
if (string.IsNullOrWhiteSpace(dbConnectionString))
{
Console.WriteLine("The configuration value for Database Connection String is missing.");
return 10;
}
var jobHostConfig = new JobHostConfiguration(webjobsConnectionString);
var host = new JobHost(jobHostConfig);
host.RunAndBlock();
return 0;
}
示例13: Main
public static void Main(string[] args) {
var configBuilder = new ConfigurationBuilder().AddCommandLine(args);
Configuration = configBuilder.Build();
string configFile = Configuration["config"];
if (configFile != null) {
configBuilder.AddJsonFile(configFile, optional: false);
Configuration = configBuilder.Build();
}
ConfigurationBinder.Bind(Configuration.GetSection("startup"), _startupOptions);
ConfigurationBinder.Bind(Configuration.GetSection("security"), _securityOptions);
_loggerFactory
.AddDebug()
.AddConsole(LogLevel.Trace)
.AddProvider(new FileLoggerProvider(_startupOptions.Name));
_logger = _loggerFactory.CreateLogger<Program>();
if (_startupOptions.Name != null) {
_logger.LogInformation(Resources.Info_BrokerName, _startupOptions.Name);
}
var tlsConfig = new TlsConfiguration(_logger, _securityOptions);
var httpsOptions = tlsConfig.GetHttpsOptions(Configuration);
Uri uri = GetServerUri(Configuration);
try {
CreateWebHost(httpsOptions).Run();
} catch(AggregateException ex) when (ex.IsPortInUseException()) {
_logger.LogError(0, ex.InnerException, Resources.Error_ConfiguredPortNotAvailable, uri?.Port);
}
}
示例14: CreateOrderProcessTask
public static void CreateOrderProcessTask([Queue("orders")] CloudQueue orderQueue)
{
Console.WriteLine("Starting Create Order Process Task");
try
{
var builder = new ConfigurationBuilder();
//builder.Add(new JsonConfigurationSource("config.json"));
builder.AddJsonFile("config.json");
var config = builder.Build();
var connectionString = config["Data:DefaultConnection:ConnectionString"];
using (var context = new PartsUnlimitedContext(connectionString))
{
var orders = context.Orders.Where(x => !x.Processed).ToList();
Console.WriteLine("Found {0} orders to process", orders.Count);
foreach (var order in orders)
{
var productIds = context.OrderDetails.Where(x => x.OrderId == order.OrderId).Select(x => x.ProductId).ToList();
var items = context.Products
.Where(x => productIds.Contains(x.ProductId))
.ToList();
var orderItems = items.Select(
x => new LegacyOrderItem
{
SkuNumber = x.SkuNumber,
Price = x.Price
}).ToList();
var queueOrder = new LegacyOrder
{
Address = order.Address,
Country = order.Country,
City = order.City,
Phone = order.Phone,
CustomerName = order.Name,
OrderDate = order.OrderDate,
PostalCode = order.PostalCode,
State = order.State,
TotalCost = order.Total,
Discount = order.Total,
Items = orderItems
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var message = JsonConvert.SerializeObject(queueOrder, settings);
orderQueue.AddMessage(new CloudQueueMessage(message));
order.Processed = true;
}
context.SaveChanges();
Console.WriteLine("Orders successfully processed.");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
示例15: ConfigureConfiguration
private static IConfiguration ConfigureConfiguration(IHostingEnvironment hostingEnvironment)
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.SetBasePath(hostingEnvironment.ContentRootPath);
configurationBuilder.AddJsonFile("config.json", optional: true);
configurationBuilder.AddEnvironmentVariables();
return configurationBuilder.Build();
}