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.
Asked
Active
Viewed 286 times
0
-
What is the framework and version of your Application? – Harshitha Apr 11 '23 at 09:40
-
1.Net framework 4.7.2 @Harshitha – devram Apr 11 '23 at 10:01
-
have you tried just using `Environment.GetEnvironmentVariable("my_env_var_name")`?! – silent Apr 11 '23 at 10:43
-
I just rephrased the title. The connection string is stored in the app service as app setting variable. – devram Apr 11 '23 at 11:52
1 Answers
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
.
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:
Azure App Service Output:

Harshitha
- 3,784
- 2
- 4
- 9