ASP.NET Core Web API 配置系统集成

文章目录


前言

集成配置系统的主要目的是将应用程序的配置信息与代码分离,使得配置信息可以在不需要修改代码的情况下进行维护。这样可以提高应用程序的灵活性和可维护性。

ASP.NET Core 提供了一种灵活的配置系统,可以轻松地将配置信息从不同的来源加载到应用程序中,并且可以根据环境变量、命令行参数、JSON 文件、XML 文件、环境变量等不同来源来管理配置。

一、配置源与默认设置

  • ASP.NET Core默认通过CreateDefaultBuilder方法预配置了多种配置源,优先级从低到高依次为:
    • appsettings.json
    • appsettings.{Environment}.json
    • 用户机密(开发环境)
    • 环境变量
    • 命令行参数

二、使用步骤

1)创建项目并添加配置

项目结构

  • AspNetCoreConfiguration
    • Controllers/
      • TestConfigurationController.cs
    • Entity/
      • AppConfig.cs
      • SmtpSettings.cs
    • appsettings.json
      • appsettings.Development.json
    • config.xml
    • Program.cs

2)配置文件

  1. appsettings.json

    csharp 复制代码
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "AppConfig": {
        "ApiName": "My API",
        "MaxRecords": 100,
        "EnableCaching": false
      }
    }
  2. appsettings.Development.json(开发环境专用)

    csharp 复制代码
    {
      "AppConfig": {
        "EnableCaching": true
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      }
    }
  3. config.xml(自定义XML配置源)

    csharp 复制代码
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    	<AppConfig>
    		<ApiName>XMLApiName热重载222</ApiName>
    		<MaxRecords>200</MaxRecords>
    		<EnableCaching>false</EnableCaching>
    	</AppConfig>
    </configuration>

3)强类型配置类

  1. AppConfig.cs

    csharp 复制代码
    namespace AspNetCoreConfiguration.Entity
    {
        public class AppConfig
        {
            public string ApiName { get; set; }
            public int MaxRecords { get; set; }
            public bool EnableCaching { get; set; }
        }
    }
  2. SmtpSettings.cs

    csharp 复制代码
    namespace AspNetCoreConfiguration.Entity
    {
        public record SmtpSettings
        {
            public string Server { get; set; }
    
            public string UserName { get; set; }
    
            public string Password {  get; set; }
        }
    }

4)配置Program.cs

  1. 示例

    csharp 复制代码
    var builder = WebApplication.CreateBuilder(args);
    //注册配置文件及它们的优先级
    builder.Configuration
        .AddJsonFile("mysettings.json", optional: true, reloadOnChange: true)
        .AddXmlFile("config.xml", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables("MyEnvironment_")
        .AddCommandLine(args);
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    //配置数据库
    builder.WebHost.ConfigureAppConfiguration((hostCtx, configBuilder) =>
    {
        string connStr = builder.Configuration.GetSection("ConnectionString").Value;
        configBuilder.AddDbConfiguration(() => new SqlConnection(connStr), reloadOnChange: true, reloadInterval: TimeSpan.FromSeconds(2));
    
    });
    
    //配置Redis
    builder.Services.AddSingleton<IConnectionMultiplexer>(sp => {
        return ConnectionMultiplexer.Connect(builder.Configuration.GetSection("Redis").Value);
    });
    
    //绑定配置节到类
    builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppConfig"));
    builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("Smtp"));
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
        //开发环境加载用户机密
        builder.Configuration.AddUserSecrets<Program>();
    }
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();

5)控制器中使用配置

  1. TestConfigurationController.cs

    csharp 复制代码
    using AspNetCoreConfiguration.Entity;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    using StackExchange.Redis;
    
    namespace AspNetCoreConfiguration.Controllers
    {
        [Route("api/[controller]/[action]")]
        [ApiController]
        public class TestConfigurationController : ControllerBase
        {
            private readonly IWebHostEnvironment _webHostEnvironment;
            private readonly AppConfig appconfig;
            private readonly SmtpSettings smtpConfig;
            private readonly IConfiguration _configuration;
            private readonly ILogger<TestConfigurationController> logger;
            private readonly IConnectionMultiplexer connectionMultiplexer;
            
            public TestConfigurationController(IWebHostEnvironment webHostEnvironment,
                IOptionsSnapshot<AppConfig> options,//支持配置热重载
                IConfiguration configuration,
                ILogger<TestConfigurationController> logger,
                IConnectionMultiplexer connectionMultiplexer,
                IOptionsSnapshot<SmtpSettings> smtpConfigOptions)
            {
                _webHostEnvironment = webHostEnvironment;
                appconfig = options.Value;
                _configuration = configuration;
                this.logger = logger;
                this.connectionMultiplexer = connectionMultiplexer;
                smtpConfig = smtpConfigOptions.Value;
            }
    
            [HttpGet]
            public string GetRedisOrSmtpConfig() {
                var pingDataBase = connectionMultiplexer.GetDatabase(0).Ping();
                logger.LogInformation($"DatabaseBase:{pingDataBase}");
                logger.LogInformation($"Smtp:{smtpConfig}");
                return "";
    
            }
            [HttpGet]
            public IActionResult GetConfigInfo()
            {
                //return Ok(new { 
                //    ApiName=appconfig.ApiName,
                //    MaxRecords = appconfig.MaxRecords,
                //    EnableCaching = appconfig.EnableCaching
                //});
                logger.LogInformation($"强类型访问appconfig.XXX:{appconfig.ApiName},{appconfig.MaxRecords},{appconfig.EnableCaching}");
                logger.LogInformation($"直接访问_configuration[AppConfig:xxx]:{_configuration["AppConfig:ApiName"]},{_configuration["AppConfig:MaxRecords"]},{_configuration["AppConfig:EnableCaching"]}");
                return Ok(_configuration["AppConfig:ApiName"]+ _configuration["AppConfig:MaxRecords"] + _configuration["AppConfig:EnableCaching"]);
    
            }
            [HttpGet]
            public string GetEnvironmentConfigValue()
            {
                return _webHostEnvironment.EnvironmentName;
            }
        }
    }

6)配置优先级测试

通过不同方式覆盖配置值

  1. 命令行参数 (最高优先级):

    csharp 复制代码
    AppConfig:ApiName=Bat_ApiName AppConfig:MaxRecords=1000 AppConfig:EnableCaching=true
  2. 环境变量 (使用双下划线 __):

  3. 用户机密 (仅Development环境):

    csharp 复制代码
    //配置secrets.json
     {
    	"AppConfig:ApiName": "user_Secrets_ApiName",
    	"AppConfig:MaxRecords": "3000",
      	"AppConfig:EnableCaching": "true",
      }

7)动态重载配置测试

  1. 修改 appsettings.jsonconfig.xml 中的值。
  2. 无需重启应用,刷新接口即可看到更新后的值(通过 IOptionsSnapshot <T> 注入)。

8)运行结果示例

  1. 假设配置优先级生效顺序为:用户机密>命令行 > 环境变量 > XML > appsettings.json
  2. 请求响应

总结

  1. 配置源优先级:后添加的源优先级更高,用户机密 > 命令行 > 环境变量 > 自定义XML >
    appsettings.{Environment}.json > appsettings.json。
  2. 强类型绑定:通过 services.Configure() 注册,使用
    IOptions <T >/IOptionsSnapshot <T> 注入。
  3. 热重载:确保 reloadOnChange: true ,并使用 IOptionsSnapshot <T > 或
    IOptionsMonitor <T>。
  4. 环境变量:使用双下划线 __ 替代层级符号(如 AppSettings__Title)。
  5. 用户机密:仅用于开发环境,通过 dotnet user-secrets 管理。
相关推荐
源码方舟2 小时前
SpringBoot + Shiro + JWT 实现认证与授权完整方案实现
java·spring boot·后端
热河暖男6 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel
noravinsc10 小时前
redis是内存级缓存吗
后端·python·django
noravinsc11 小时前
django中用 InforSuite RDS 替代memcache
后端·python·django
喝醉的小喵11 小时前
【mysql】并发 Insert 的死锁问题 第二弹
数据库·后端·mysql·死锁
kaixin_learn_qt_ing12 小时前
Golang
开发语言·后端·golang
炒空心菜菜13 小时前
MapReduce 实现 WordCount
java·开发语言·ide·后端·spark·eclipse·mapreduce
wowocpp15 小时前
spring boot Controller 和 RestController 的区别
java·spring boot·后端
后青春期的诗go15 小时前
基于Rust语言的Rocket框架和Sqlx库开发WebAPI项目记录(二)
开发语言·后端·rust·rocket框架
freellf15 小时前
go语言学习进阶
后端·学习·golang