简体   繁体   中英

Environment Variables in web.config

Working on a webapp on VS2017 using MVC framework on .NET 4.5. In my local dev environment, I use the web.config file something like this:

<appSettings>
    <add key="GOOGLE_APPLICATION_CREDENTIALS" 
         value="C:\\Work\\Services-abcd.json" /> 
</appSettings>

But when I run the webapp I still get the error that GOOGLE_APPLICATION_CREDENTIALS is undefined.

So my question specifically is:

  1. Where am I going wrong? Do I need to define it somewhere else?
  2. When I deploy this to staging/production, on my azure web service, how will I share the json file and how will the web.config file need to change for that?

I know this question answers how to get the variables in web.config, but somehow I am not able to set it there.

Edit 1: Since I was asked, here is where I am getting the error of missing environment variable-

using Google.Cloud.Translation.V2;

TranslationClient client = TranslationClient.Create();

I am unable to declare TranslationClient.

Where am I going wrong? Do I need to define it somewhere else?

According to your codes and description, I found you have defined the app setting not the environment variables. Notice: app setting isn't as same as environment variables.

If you want to set environment variables in the azure web app, I suggest you could set it in your web application codes and upload the application to the app service as below:

   Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Server.MapPath("test/test.txt"));

When I deploy this to staging/production, on my azure web service, how will I share the json file and how will the web.config file need to change for that?

I suggest you could create a folder to store the json file in your web application, then you could use Server.MapPath to get the right path of your json file.

Since I don't have the google cloud app credentials json file, so I add a txt file in my test demo to test the code could work well.

More details about my test demo, you could refer to below codes.

 protected void Page_Load(object sender, EventArgs e)
        {
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Server.MapPath("test/test.txt"));
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
           string path =  Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");

            Response.Write(path + "\n");

            string[] lines = System.IO.File.ReadAllLines(path);

            foreach (string line in lines)
            {

                Response.Write(line);
            }

        }

Result(111 is the txt file content):

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM