You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取存储在App Service应用设置中的Azure Cache for Redis连接字符串

从Azure App Service应用设置中读取Redis连接字符串

根据你使用的.NET框架版本,以下是两种常见的实现方式:

.NET Framework 场景

如果你之前的项目基于.NET Framework,直接使用ConfigurationManager读取即可,App Service的应用设置会自动覆盖web.config中的同名配置项:

using System.Configuration;

// 读取应用设置中的Redis连接字符串(对应Terraform设置的键名)
string redisConnStr = ConfigurationManager.AppSettings["RedisConnectionString"];

// 如果你的Terraform是将连接字符串配置在ConnectionStrings节,用下面的方式:
// string redisConnStr = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString;

.NET Core/.NET 5+ 场景

对于.NET Core及更高版本,通过依赖注入的IConfiguration来读取配置:

  1. 确保项目已默认加载配置(.NET 6+顶级语句模式下无需额外配置)
  2. 在需要使用连接字符串的类中注入IConfiguration:
public class RedisClientService
{
    private readonly string _redisConnStr;

    // 构造函数注入IConfiguration
    public RedisClientService(IConfiguration configuration)
    {
        // 读取应用设置中的Redis连接字符串
        _redisConnStr = configuration["RedisConnectionString"];

        // 若配置在ConnectionStrings节点,使用以下方式:
        // _redisConnStr = configuration.GetConnectionString("RedisConnectionString");
    }
}

关键注意事项

  • 确保代码中使用的配置键名,和你Terraform中设置的App Service应用设置键完全一致,例如Terraform配置片段:
    resource "azurerm_app_service" "your_app" {
      # 其他配置项...
      app_settings = {
        "RedisConnectionString" = azurerm_redis_cache.your_redis.primary_connection_string
      }
    }
    
  • 本地开发时,可在appsettings.json(.NET Core)或web.config(.NET Framework)中添加同名配置项进行测试,部署到Azure后会自动优先使用App Service的云端配置。

内容的提问来源于stack exchange,提问作者devram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:22:03