8. 配置文件

IoT Gateway 使用多种配置文件来管理系统的各种设置,包括应用配置、数据库配置、日志配置等。这些配置文件采用 JSON 格式,便于编辑和管理。

Iotgateway 网关

8.1 配置文件概述

8.1.1 主要配置文件

配置文件用途位置
appsettings.json应用主配置文件IoTGateway/appsettings.json
appsettings.Development.json开发环境配置文件IoTGateway/appsettings.Development.json
appsettings.Production.json生产环境配置文件IoTGateway/appsettings.Production.json
launchSettings.json启动配置文件IoTGateway/Properties/launchSettings.json
dotnet-tools.json.NET 工具配置IoTGateway/.config/dotnet-tools.json

8.1.2 配置加载顺序

  1. 环境变量

  2. 命令行参数

  3. appsettings.{Environment}.json

  4. appsettings.json

  5. 其他配置源(如 Azure Key Vault、AWS Secrets Manager 等)

8.2 应用主配置文件(appsettings.json)

appsettings.json 是网关的主配置文件,包含了系统的核心配置信息。

8.2.1 配置结构

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Connections": [
    {
      "Name": "Default",
      "DBType": "sqlite",
      "Value": "Data Source=iotgateway.db"
    }
  ],
  "JwtSettings": {
    "SecretKey": "your-secret-key",
    "Issuer": "iotgateway",
    "Audience": "iotgateway-client",
    "ExpiresInMinutes": 30
  },
  "CorsSettings": {
    "AllowOrigins": ["*"],
    "AllowMethods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    "AllowHeaders": ["*"],
    "AllowCredentials": true
  },
  "SwaggerSettings": {
    "Enabled": true,
    "Title": "IoT Gateway API",
    "Version": "v1",
    "Description": "IoT Gateway API Documentation"
  },
  "MultiLanguageSettings": {
    "Enabled": true,
    "DefaultLanguage": "zh-CN",
    "SupportedLanguages": ["zh-CN", "en-US"]
  }
}

8.2.2 配置项说明

8.2.2.1 Logging(日志配置)
配置项类型描述默认值
LogLevel.Defaultstring默认日志级别Information
LogLevel.Microsoft.AspNetCorestringASP.NET Core 日志级别Warning
8.2.2.2 AllowedHosts(允许的主机)
配置项类型描述默认值
AllowedHostsstring允许访问的主机名*(允许所有主机)
8.2.2.3 Connections(数据库连接配置)
配置项类型描述默认值
Namestring连接名称Default
DBTypestring数据库类型(sqlite、mysql、pgsql、oracle)sqlite
Valuestring数据库连接字符串Data Source=iotgateway.db
8.2.2.4 JwtSettings(JWT 配置)
配置项类型描述默认值
SecretKeystringJWT 密钥your-secret-key
IssuerstringJWT 签发者iotgateway
AudiencestringJWT 接收者iotgateway-client
ExpiresInMinutesintJWT 过期时间(分钟)30
8.2.2.5 CorsSettings(CORS 配置)
配置项类型描述默认值
AllowOriginsarray允许的源["*"]
AllowMethodsarray允许的 HTTP 方法["GET", "POST", "PUT", "DELETE", "OPTIONS"]
AllowHeadersarray允许的 HTTP 头["*"]
AllowCredentialsbool是否允许凭据true
8.2.2.6 SwaggerSettings(Swagger 配置)
配置项类型描述默认值
Enabledbool是否启用 Swaggertrue
TitlestringSwagger 文档标题IoT Gateway API
VersionstringAPI 版本v1
DescriptionstringAPI 描述IoT Gateway API Documentation
8.2.2.7 MultiLanguageSettings(多语言配置)
配置项类型描述默认值
Enabledbool是否启用多语言true
DefaultLanguagestring默认语言zh-CN
SupportedLanguagesarray支持的语言列表["zh-CN", "en-US"]

8.3 环境配置文件

8.3.1 开发环境配置(appsettings.Development.json)

开发环境配置文件,包含了开发环境的特定配置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft.AspNetCore": "Information"
    }
  },
  "Connections": [
    {
      "Name": "Default",
      "DBType": "sqlite",
      "Value": "Data Source=iotgateway-dev.db"
    }
  ]
}

8.3.2 生产环境配置(appsettings.Production.json)

生产环境配置文件,包含了生产环境的特定配置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.AspNetCore": "Error"
    }
  },
  "Connections": [
    {
      "Name": "Default",
      "DBType": "mysql",
      "Value": "Server=localhost;Database=iotgateway;User=root;Password=your-password;"
    }
  ],
  "JwtSettings": {
    "SecretKey": "your-production-secret-key",
    "ExpiresInMinutes": 60
  }
}

8.4 启动配置文件(launchSettings.json)

launchSettings.json 包含了应用的启动配置信息,如启动 URL、环境变量等。

8.4.1 配置结构

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IoTGateway": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:518;https://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

8.4.2 配置项说明

配置项类型描述
$schemastringJSON Schema URL
iisSettingsobjectIIS 配置
profilesobject启动配置文件列表
profiles.IIS ExpressobjectIIS Express 启动配置
profiles.IoTGatewayobject项目直接启动配置
commandNamestring命令名称(IISExpress、Project、Docker 等)
launchBrowserbool是否自动启动浏览器
launchUrlstring启动 URL
applicationUrlstring应用 URL
environmentVariablesobject环境变量

8.5 .NET 工具配置(dotnet-tools.json)

dotnet-tools.json 包含了项目使用的 .NET 工具配置:

{
  "version": 1,
  "isRoot": true,
  "tools": {
    "microsoft.extensions.secretmanager.tools": {
      "version": "6.0.0",
      "commands": [
        "dotnet-user-secrets"
      ]
    },
    "microsoft.dotnet-httprepl": {
      "version": "6.0.0",
      "commands": [
        "httprepl"
      ]
    },
    "swashbuckle.aspnetcore.cli": {
      "version": "6.2.3",
      "commands": [
        "swagger"
      ]
    }
  }
}

8.6 配置管理 API

8.6.1 配置注入

使用依赖注入获取配置:

public class MyService
{
    private readonly IConfiguration _configuration;
    
    public MyService(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    
    public void DoSomething()
    {
        // 读取配置
        var connectionString = _configuration.GetConnectionString("Default");
        var logLevel = _configuration["Logging:LogLevel:Default"];
    }
}

8.6.2 强类型配置

将配置绑定到强类型对象:

// 定义配置类
public class JwtSettings
{
    public string SecretKey { get; set; }
    public string Issuer { get; set; }
    public string Audience { get; set; }
    public int ExpiresInMinutes { get; set; }
}
​
// 在 Startup.cs 中配置
public void ConfigureServices(IServiceCollection services)
{
    // 绑定配置
    services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
}
​
// 使用强类型配置
public class MyService
{
    private readonly JwtSettings _jwtSettings;
    
    public MyService(IOptions<JwtSettings> jwtSettings)
    {
        _jwtSettings = jwtSettings.Value;
    }
    
    public void DoSomething()
    {
        // 使用配置
        var secretKey = _jwtSettings.SecretKey;
        var expiresInMinutes = _jwtSettings.ExpiresInMinutes;
    }
}

8.7 配置热重载

8.7.1 启用配置热重载

在 Program.cs 中启用配置热重载:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            // 启用配置热重载
            config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

8.7.2 监听配置变化

使用 IOptionsMonitor 监听配置变化:

public class MyService : IDisposable
{
    private readonly IOptionsMonitor<JwtSettings> _jwtSettingsMonitor;
    private IDisposable _registration;
    
    public MyService(IOptionsMonitor<JwtSettings> jwtSettingsMonitor)
    {
        _jwtSettingsMonitor = jwtSettingsMonitor;
        
        // 监听配置变化
        _registration = _jwtSettingsMonitor.OnChange(settings =>
        {
            // 配置变化时的处理逻辑
            Console.WriteLine($"JWT 配置已更新: {settings.SecretKey}");
        });
    }
    
    public void Dispose()
    {
        _registration?.Dispose();
    }
}

8.8 环境变量配置

8.8.1 环境变量格式

环境变量使用以下格式:

  • 层级之间使用 __(双下划线)分隔

  • 数组使用索引表示

示例

  • Logging__LogLevel__Default 对应 Logging:LogLevel:Default

  • Connections__0__DBType 对应 Connections[0].DBType

8.8.2 设置环境变量

Windows

set ASPNETCORE_ENVIRONMENT=Production
set Logging__LogLevel__Default=Warning

Linux/macOS

export ASPNETCORE_ENVIRONMENT=Production
export Logging__LogLevel__Default=Warning

8.9 命令行参数配置

8.9.1 命令行参数格式

命令行参数使用以下格式:

  • 使用 -- 前缀

  • 层级之间使用 : 分隔

示例

dotnet run -- --Logging:LogLevel:Default=Warning --Connections:0:DBType=mysql

8.9.2 读取命令行参数

命令行参数会自动添加到配置中,可以通过 IConfiguration 读取:

public class MyService
{
    private readonly IConfiguration _configuration;
    
    public MyService(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    
    public void DoSomething()
    {
        // 读取命令行参数
        var logLevel = _configuration["Logging:LogLevel:Default"];
    }
}

8.10 配置安全

8.10.1 敏感数据保护

  • 避免在配置文件中存储明文密码和密钥

  • 使用环境变量或密钥管理服务存储敏感数据

  • 对敏感数据进行加密

8.10.2 密钥管理服务

支持的密钥管理服务:

  • Azure Key Vault

  • AWS Secrets Manager

  • HashiCorp Vault

  • 本地密钥管理服务

8.10.3 配置文件访问控制

  • 限制配置文件的访问权限

  • 定期更换密钥和密码

  • 审计配置文件的访问

8.11 配置最佳实践

8.11.1 配置分离

  • 将不同环境的配置分离到不同的配置文件

  • 将敏感数据与非敏感数据分离

  • 将应用配置与基础设施配置分离

8.11.2 配置验证

  • 对配置进行验证,确保配置的完整性和正确性

  • 使用数据注解或 Fluent Validation 进行配置验证

  • 在应用启动时验证配置

8.11.3 配置文档

  • 为配置项添加详细的注释

  • 维护配置文档

  • 定期更新配置文档

8.11.4 配置版本控制

  • 将配置文件纳入版本控制

  • 记录配置变更历史

  • 支持配置回滚

8.12 配置示例

8.12.1 MySQL 配置示例

{
  "Connections": [
    {
      "Name": "Default",
      "DBType": "mysql",
      "Value": "Server=localhost;Port=3306;Database=iotgateway;User=root;Password=your-password;CharSet=utf8mb4;"
    }
  ]
}

8.12.2 PostgreSQL 配置示例

{
  "Connections": [
    {
      "Name": "Default",
      "DBType": "pgsql",
      "Value": "Host=localhost;Port=5432;Database=iotgateway;Username=postgres;Password=your-password;"
    }
  ]
}

8.12.3 Oracle 配置示例

{
  "Connections": [
    {
      "Name": "Default",
      "DBType": "oracle",
      "Value": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User Id=iotgateway;Password=your-password;"
    }
  ]
}

文档版本:1.0 更新日期:2025-11-29 编写人员:辉为科技

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐