当前位置: 首页>>代码示例>>C#>>正文


C# IConfiguration.GetSection方法代码示例

本文整理汇总了C#中IConfiguration.GetSection方法的典型用法代码示例。如果您正苦于以下问题:C# IConfiguration.GetSection方法的具体用法?C# IConfiguration.GetSection怎么用?C# IConfiguration.GetSection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IConfiguration的用法示例。


在下文中一共展示了IConfiguration.GetSection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ConfigureOptionsServices

        /// <summary>
        /// Configures the settings by binding the contents of the config.json file to the specified Plain Old CLR 
        /// Objects (POCO) and adding <see cref="IOptions{}"/> objects to the services collection.
        /// </summary>
        /// <param name="services">The services collection or IoC container.</param>
        /// <param name="configuration">Gets or sets the application configuration, where key value pair settings are 
        /// stored.</param>
        private static void ConfigureOptionsServices(IServiceCollection services, IConfiguration configuration)
        {
            // Adds IOptions<AppSettings> to the services container.
            services.Configure<AppSettings>(configuration.GetSection(nameof(AppSettings)));

            // Adds IOptions<CacheProfileSettings> to the services container.
            services.Configure<CacheProfileSettings>(configuration.GetSection(nameof(CacheProfileSettings)));
        }
开发者ID:modulexcite,项目名称:ASP.NET-MVC-Boilerplate,代码行数:15,代码来源:Startup.Options.cs

示例2: AddDaniel15Config

 public static void AddDaniel15Config(this IServiceCollection services, IConfiguration config)
 {
     services.AddSingleton(_ => config);
     services.Configure<SiteConfiguration>(config.GetSection("Site"));
     services.Configure<GalleryConfiguration>(config.GetSection("Gallery"));
     services.AddSingleton<ISiteConfiguration>(
         provider => provider.GetRequiredService<IOptions<SiteConfiguration>>().Value
     );
     services.AddSingleton<IGalleryConfiguration>(
         provider => provider.GetRequiredService<IOptions<GalleryConfiguration>>().Value
     );
 }
开发者ID:Daniel15,项目名称:Website,代码行数:12,代码来源:Ioc.cs

示例3: StopsServiceOptions

        public StopsServiceOptions(IConfiguration config, IApplicationEnvironment appEnv)
        {
            FilePath = Path.Combine(appEnv.ApplicationBasePath,
                config.GetSection("DataSource:FilePath").Value);

            // optional parameters
            var delimiter = config.GetSection("DataSource:Delimiter").Value;
            var hasHeader = config.GetSection("DataSource:HasHeader").Value;
            var hasQuotes = config.GetSection("DataSource:HasQuotes").Value;

            Delimiter = delimiter?[0] ?? DelimiterDefault;
            HasHeader = hasHeader == null ? HasHeaderDefault : bool.Parse(hasHeader);
            HasQuotes = hasQuotes == null ? HasQuotesDefault : bool.Parse(hasQuotes);
        }
开发者ID:AndriiMysnyk,项目名称:angular-mvc6-test-task,代码行数:14,代码来源:StopsServiceOptions.cs

示例4: ConfigureLogging

        /// <summary>
        /// Configure tools used to help with logging internal application events.
        /// See http://docs.asp.net/en/latest/fundamentals/logging.html
        /// </summary>
        /// <param name="environment">The environment the application is running under. This can be Development,
        /// Staging or Production by default.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="configuration">Gets or sets the application configuration, where key value pair settings are
        /// stored.</param>
        private static void ConfigureLogging(
            IHostingEnvironment environment,
            ILoggerFactory loggerFactory,
            IConfiguration configuration)
        {
            // Add the following to the request pipeline only in development environment.
            if (environment.IsDevelopment())
            {
                // Add the console logger.
                loggerFactory.AddConsole(configuration.GetSection(LoggingConfigurationSectionName));

                // Add the debug logger.
                loggerFactory.AddDebug();
            }

            // Log to the Windows event log (Full .NET Framework Only).
            // Add the Microsoft.Extensions.Logging.EventLog package.
            // #if NET461
            // loggerFactory.AddEventLog(
            //     new EventLogSettings()
            //     {
            //         SourceName = configuration.GetValue<AppSettings>(nameof(AppSettings)).SiteTitle
            //     });
            // #endif

            // Log to Serilog (See https://github.com/serilog/serilog-framework-logging).
            // loggerFactory.AddSerilog();
        }
开发者ID:tzerb,项目名称:Learning,代码行数:37,代码来源:Startup.Logging.cs

示例5: Read

        public void Read(IConfiguration configuration)
        {
            var value = configuration["RetryCount"];
            if (!string.IsNullOrEmpty(value))
            {
                RetryCount = int.Parse(value);
            }
			value = configuration["DefaultAdBlock"];
            if (!string.IsNullOrEmpty(value))
            {
                DefaultAdBlock = value;
            }

            var items = new List<AdBlock>();
            foreach (var subConfig in configuration.GetSection("AdBlock").GetChildren())
            {
                var item = new AdBlock { Name = subConfig.Key };
				value = subConfig["Origin"];
                if (!string.IsNullOrEmpty(value))
                {
                    item.Origin = value;
                }
				value = subConfig["ProductCode"];
                if (!string.IsNullOrEmpty(value))
                {
                    item.ProductCode = value;
                }
                items.Add(item);
            }
            AdBlocks = items.ToDictionary(
                item => item.Name, 
                item => item,
                StringComparer.OrdinalIgnoreCase);
        }
开发者ID:leloulight,项目名称:Entropy,代码行数:34,代码来源:MySettings.cs

示例6: LoadLoggerToLoggingConfig

 public static void LoadLoggerToLoggingConfig(LoggingConfiguration logConfig, IConfiguration Configuration,string sectionString)
 {
     var fileLoggerSection = Configuration.GetSection(sectionString).GetChildren();
     foreach (var logging in fileLoggerSection)
     {
         var target = new FileTarget()
         {
             FileName = logging["fileName"],
             Name = logging["name"],
             Layout = logging["layoutFormat"]
         };
         var minLevel = logging["minLevel"] != null ? LogLevel.FromString(logging["minLevel"]) : null;
         LoggingRule rule = null;
         if (minLevel != null)
         {
             rule = new LoggingRule(logging["namePattern"], minLevel, target);
         }
         else
         {
             rule = new LoggingRule(logging["namePattern"], target);
         }
         var useLevels = logging["logLevel"];
         if(string.IsNullOrWhiteSpace(useLevels) == false)
         {
             var levels = useLevels.Split(',');
             foreach (var level in levels)
             {
                 rule.EnableLoggingForLevel(LogLevel.FromString(level));
             }
         }
         logConfig.AddTarget(target);
         logConfig.LoggingRules.Add(rule);
     }
 }
开发者ID:Sharelink,项目名称:BahamutZero,代码行数:34,代码来源:LoggerLoaderHelper.cs

示例7: WithConfiguration

        public static MongoDbAuditStoreProvider WithConfiguration(
            this MongoDbAuditStoreProvider @mongoDbAuditStoreProvider, IConfiguration configuration)
        {
            var configSection = configuration.GetSection($"{nameof(MongoDbAuditStoreProvider)}");
            if (configSection == null)
                throw new ArgumentException(
                    $"Not configuration section named {nameof(MongoDbAuditStoreProvider)} found.");
            if (!configSection.GetChildren().Any())
                throw new ArgumentException(
                    $"Configuration section {nameof(MongoDbAuditStoreProvider)} did not contain any settings.");

            var serverName = configSection["Server"];
            var timeoutMilliseconds = configSection["TimeoutMilliseconds"];
            var databaseName = configSection["DatabaseName"];
            var collectionName = configSection["CollectionName"];

            @mongoDbAuditStoreProvider.ServerName = string.IsNullOrEmpty(serverName)
                ? @mongoDbAuditStoreProvider.ServerName
                : serverName;
            @mongoDbAuditStoreProvider.TimeoutMilliseconds = string.IsNullOrEmpty(timeoutMilliseconds)
                ? @mongoDbAuditStoreProvider.TimeoutMilliseconds
                : int.Parse(timeoutMilliseconds);
            @mongoDbAuditStoreProvider.DatabaseName = string.IsNullOrEmpty(databaseName)
                ? @mongoDbAuditStoreProvider.DatabaseName
                : databaseName;
            @mongoDbAuditStoreProvider.CollectionName = string.IsNullOrEmpty(collectionName)
                ? @mongoDbAuditStoreProvider.CollectionName
                : collectionName;

            return @mongoDbAuditStoreProvider;
        }
开发者ID:johannbrink,项目名称:EFAuditing,代码行数:31,代码来源:MongoDbAuditStoreProviderExtensions.cs

示例8: RegisterConfiguredModules

        /// <summary>
        /// Registers individual configured modules into a container builder.
        /// </summary>
        /// <param name="builder">
        /// The <see cref="Autofac.ContainerBuilder"/> that should receive the configured registrations.
        /// </param>
        /// <param name="configuration">
        /// The <see cref="IConfiguration"/> containing the configured registrations.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="builder"/> or <paramref name="configuration"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown if there is any issue in parsing the module configuration into registrations.
        /// </exception>
        /// <remarks>
        /// <para>
        /// This is where the individually configured component registrations get added to the <paramref name="builder"/>.
        /// The <c>modules</c> collection from the <paramref name="configuration"/>
        /// get processed into individual modules which are instantiated and activated inside the <paramref name="builder"/>.
        /// </para>
        /// </remarks>
        public virtual void RegisterConfiguredModules(ContainerBuilder builder, IConfiguration configuration)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            var defaultAssembly = configuration.DefaultAssembly();
            foreach (var moduleElement in configuration.GetSection("modules").GetChildren())
            {
                var moduleType = moduleElement.GetType("type", defaultAssembly);
                var module = (IModule)null;
                using (var moduleActivator = new ReflectionActivator(
                    moduleType,
                    new DefaultConstructorFinder(),
                    new MostParametersConstructorSelector(),
                    moduleElement.GetParameters("parameters"),
                    moduleElement.GetProperties("properties")))
                {
                    module = (IModule)moduleActivator.ActivateInstance(new ContainerBuilder().Build(), Enumerable.Empty<Parameter>());
                }
                builder.RegisterModule(module);
            }
        }
开发者ID:MyLobin,项目名称:Autofac.Configuration,代码行数:50,代码来源:ModuleRegistrar.cs

示例9: ConfigurationLoginProviders

 public ConfigurationLoginProviders(IConfiguration config)
 {
     Facebook = GetProvider(config, nameof(Facebook));
     Google = GetProvider(config, nameof(Google));
     Microsoft = GetProvider(config, nameof(Microsoft));
     Twitter = GetProvider(config, nameof(Twitter));
     Azure = new AzureADLoginProviderCredentials(config.GetSection(nameof(Azure)));
 }
开发者ID:Ranireddy,项目名称:PartsUnlimited,代码行数:8,代码来源:ConfigurationLoginProviders.cs

示例10: AddAuthentication

        public static IServiceCollection AddAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<GoogleAuthSettings>(configuration.GetSection("GoogleAuthSettings"));
            services.Configure<MicrosoftAuthSettings>(configuration.GetSection("MicrosoftAuthSettings"));
            services.AddSingleton<AuthManager>();

            var policy = new AuthorizationPolicyBuilder()
                .RequireClaim("dg:org")
                .RequireClaim("dg:role")
                .Build();

            services.AddAuthorization(options =>
                {
                    options.DefaultPolicy = policy;
                });
                
            return services;
        }
开发者ID:HopeNB,项目名称:web,代码行数:18,代码来源:AuthConfiguration.cs

示例11: ConfigureLogging

        /// <summary>
        /// Configure tools used to help with logging internal application events.
        /// See http://docs.asp.net/en/latest/fundamentals/logging.html
        /// </summary>
        /// <param name="application">The application.</param>
        /// <param name="environment">The environment the application is running under. This can be Development, 
        /// Staging or Production by default.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="configuration">Gets or sets the application configuration, where key value pair settings are 
        /// stored.</param>
        private static void ConfigureLogging(
            IApplicationBuilder application,
            IHostingEnvironment environment,
            ILoggerFactory loggerFactory,
            IConfiguration configuration)
        {
            // Add the following to the request pipeline only in development environment.
            if (environment.IsDevelopment())
            {
                // Set the minimum logging level to log all log messages. See details below:
                loggerFactory.MinimumLevel = LogLevel.Debug;
                // Debug - Used for the most detailed log messages, typically only valuable to a developer debugging an 
                //     issue.These messages may contain sensitive application data and so should not be enabled in a 
                //     production environment.Disabled by default.
                //     Example: 'Credentials: { "User":"someuser", "Password":"[email protected]"}'.
                // Verbose - These messages have short-term usefulness during development.They contain information that 
                //     may be useful for debugging, but have no long - term value.This is the default most verbose 
                //     level of logging. Example: 'Entering method Configure with flag set to true'.
                // Information - These messages are used to track the general flow of the application.These logs should 
                //     have some long term value, as opposed to Verbose level messages, which do not.
                //     Example: 'Request received for path / foo'.
                // Warning - The Warning level should be used for abnormal or unexpected events in the application 
                //     flow.These may include errors or other conditions that do not cause the application to stop, but 
                //     which may need to be investigated in the future. Handled exceptions are a common place to use 
                //     the Warning log level. 
                //     Examples: 'Login failed for IP 127.0.0.1' or 'FileNotFoundException for file foo.txt'.
                // Error - An error should be logged when the current flow of the application must stop due to some 
                //     failure, such as an exception that cannot be handled or recovered from.These messages should 
                //     indicate a failure in the current activity or operation(such as the current HTTP request), not 
                //     an application - wide failure. Example: 'Cannot insert record due to duplicate key violation'.
                // Critical - A critical log level should be reserved for unrecoverable application or system crashes, 
                //     or catastrophic failure that requires immediate attention.
                //     Examples: 'data loss scenarios', 'stack overflows', 'out of disk space'.

                // Add the console logger.
                loggerFactory.AddConsole(configuration.GetSection(LoggingConfigurationSectionName));

                // Add the debug logger.
                loggerFactory.AddDebug();
            }
            else
            {
                // Set the minimum logging level to log information level log messages. See details above:
                loggerFactory.MinimumLevel = LogLevel.Information;
            }

            // Log warning level messages and above to the Windows event log.
            // var sourceSwitch = new SourceSwitch("EventLog");
            // sourceSwitch.Level = SourceLevels.Information;
            // loggerFactory.AddTraceSource(sourceSwitch, new EventLogTraceListener("Application"));

            // Log to NLog (See https://github.com/aspnet/Logging/tree/1.0.0-beta6/src/Microsoft.Framework.Logging.NLog).
            // loggerFactory.AddNLog(new NLog.LogFactory());

            // Log to Serilog (See https://github.com/serilog/serilog-framework-logging).
            // loggerFactory.AddSerilog();
        }
开发者ID:HoussemRomdhani,项目名称:ASP.NET-MVC-Boilerplate,代码行数:67,代码来源:Startup.Logging.cs

示例12: AddRaygun

    public static IServiceCollection AddRaygun(this IServiceCollection services, IConfiguration configuration, RaygunMiddlewareSettings middlewareSettings)
    {
      services.Configure<RaygunSettings>(configuration.GetSection("RaygunSettings"));

      services.AddTransient(_ => middlewareSettings.ClientProvider ?? new DefaultRaygunAspNetCoreClientProvider());
      services.AddTransient(_ => middlewareSettings);

      return services;
    }
开发者ID:MindscapeHQ,项目名称:raygun4net,代码行数:9,代码来源:RaygunAspNetMiddleware.cs

示例13: ConfigureCacheProfiles

        /// <summary>
        /// Controls how controller actions cache content in one central location.
        /// </summary>
        /// <param name="cacheProfiles">The settings for the <see cref="ResponseCacheAttribute"/>'s.</param>
        /// <param name="configuration">Gets or sets the application configuration, where key value pair settings are 
        /// stored.</param>
        private static void ConfigureCacheProfiles(IDictionary<string, CacheProfile> cacheProfiles, IConfiguration configuration)
        {
            var configurationSection = configuration.GetSection(nameof(CacheProfileSettings));
            CacheProfileSettings cacheProfileSettings = new CacheProfileSettings();
            ConfigurationBinder.Bind(configurationSection, cacheProfileSettings);

            foreach (KeyValuePair<string, CacheProfile> keyValuePair in cacheProfileSettings.CacheProfiles)
            {
                cacheProfiles.Add(keyValuePair);
            }
        }
开发者ID:Pro-Coded,项目名称:Pro.MVCMagic,代码行数:17,代码来源:Startup.CacheProfiles.cs

示例14: ConfigureSwagger

        /// <summary>
        /// Configures swagger. See https://github.com/domaindrivendev/Swashbuckle
        /// </summary>
        /// <param name="services">The services collection or IoC container.</param>
        /// <param name="configuration">Gets or sets the application configuration, where key value pair settings are 
        /// stored.</param>
        private static void ConfigureSwagger(IServiceCollection services, IConfiguration configuration)
        {
            var configurationSection = configuration.GetSection(nameof(AppSettings));
            AppSettings appSettings = new AppSettings();
            ConfigurationBinder.Bind(configurationSection, appSettings);

            services.AddSwagger(
                x =>
                {
                    // Use strings instead of integers to describe enumerations by default.
                    x.SchemaGeneratorOptions.DescribeAllEnumsAsStrings = true;

                    // If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access
                    // the docs is taken as the default. If your API supports multiple schemes and you want to be 
                    // explicit about them, you can use the "Schemes" option as shown below.
                    x.SwaggerGeneratorOptions.Schemes =
                        new string[]
                        {
                            "http",
                            "https"
                        };

                    // Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object 
                    // to hold additional metadata for an API.
                    x.SwaggerGeneratorOptions.SingleApiVersion(
                        new Info()
                        {
                            Version = "v1",
                            Title = appSettings.SiteTitle,
                            Description = appSettings.SiteDescription,
                            TermsOfService = appSettings.SiteTermsOfService,
                            Contact = new Swashbuckle.Swagger.Contact()
                            {
                                Name = appSettings.Contact.Name,
                                Email= appSettings.Contact.Email,
                                Url = appSettings.Contact.Url
                            },
                            License = new Swashbuckle.Swagger.License()
                            {
                                Name = appSettings.License.Name,
                                Url = appSettings.License.Url,
                            }
                        });

                    // If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
                    // In this case, you must provide a collection of Info objects for each version of your API and
                    // a lambda that tells Swashbuckle which actions should be included in the docs for a given API 
                    // version.
                    // x.SwaggerGeneratorOptions.MultipleApiVersions(
                    //     GetApiVersions,
                    //     (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion));
                });
        }
开发者ID:modulexcite,项目名称:ASP.NET-MVC-Boilerplate,代码行数:59,代码来源:Startup.Swagger.cs

示例15: ConfigurationElasticClientSettings

        public ConfigurationElasticClientSettings(IConfiguration configuration)
        {
            ConnectionString = (configuration.Get<string>("ELASTICSEARCH_PORT")).Replace("tcp", "http");
            Uri uri = new Uri(ConnectionString);

            var elasticConfig = configuration.GetSection("ElasticSearch");
            int count;
            int.TryParse(elasticConfig.Get<string>("DefaultItemCount"), out count);
            DefaultItemCount = count;

            ConnectionSettings cs = new ConnectionSettings(uri, elasticConfig.Get<string>("DefaultIndex"));
            Client = new ElasticClient(cs);
        }
开发者ID:flakio,项目名称:catalog,代码行数:13,代码来源:ConfigurationElasticClientSettings.cs


注:本文中的IConfiguration.GetSection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。