0

I have created a azure redis for cache and stored the connection string as application setting variable in app service using terraform. Now I want my code to access the connection string. In the existing application we explictly mentioned the connection string in web.config. So now I needed to get the azure application variable via code.

devram
  • 105
  • 2
  • 11

1 Answers1

0

I have referred this MSDoc to set and retrieve Redis Cache Connection String.

My Web.config file App Setting:

 <appSettings>
    <add key="RedisCacheConn" value="HarshuRedisCache.redis.cache.windows.net:6380,password=**********=,ssl=True,abortConnect=False"/>
 </appSettings>

In Controller :

 public ActionResult Index()
        {
            string RCConn = ConfigurationManager.AppSettings["RedisCacheConn"].ToString();
            string rediscon = Environment.GetEnvironmentVariable("RedisCacheConn");
            ViewBag.RCConn = RCConn.ToString();
            if (rediscon != null)
            {
                ViewBag.rediscon = rediscon.ToString();
            }
            return View();
        }

Index.cshtml :

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h5> <b>With ConfigurationManager </b> - @ViewBag.RCConn</h5>
    <h5> <b>With Environment Variable</b> - @ViewBag.rediscon</h5>
</div>

Thanks @Silent for the Comment.

As mentioned by Silent we can also use Environment.GetEnvironmentVariable("RedisCacheConn"); to retrieve the App setting variable.

For this we need to set the App setting in the Configuration Section of the App Service.

enter image description here

  • This is for the deployed Azure Web App.

  • To get the value with Environment variable locally, we need to set the value locally.

Local Output: enter image description here

Azure App Service Output:

enter image description here

Harshitha
  • 3,784
  • 2
  • 4
  • 9