使用 .NET 4.5 上的 MVC 框架在 VS2017 上开发 Web 应用程序。在我的本地开发环境中,我使用类似这样的 web.config 文件:
<appSettings>
<add key="GOOGLE_APPLICATION_CREDENTIALS"
value="C:\\Work\\Services-abcd.json" />
</appSettings>
但是当我运行 webapp 时,我仍然收到 GOOGLE_APPLICATION_CREDENTIALS 未定义的错误。
所以我的问题具体是:
- 我哪里出错了?我需要在其他地方定义它吗?
- 当我将其部署到暂存/生产环境时,在我的 Azure Web 服务上,我将如何共享 json 文件以及 web.config 文件需要如何更改?
我知道this question回答了如何在 web.config 中获取变量,但不知何故我无法在那里设置它。
编辑 1:自从有人问我以来,这是我收到缺少环境变量错误的地方-
using Google.Cloud.Translation.V2;
TranslationClient client = TranslationClient.Create();
我无法声明 TranslationClient。
请您参考如下方法:
Where am I going wrong? Do I need to define it somewhere else?
根据您的代码和描述,我发现您定义的是应用程序设置而不是环境变量。注意:应用设置不同于环境变量。
如果你想在 azure web 应用程序中设置环境变量,我建议你可以在你的 web 应用程序代码中设置它,然后将应用程序上传到应用程序服务,如下所示:
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?
我建议您可以在您的 Web 应用程序中创建一个文件夹来存储 json 文件,然后您可以使用 Server.MapPath 来获取您的 json 文件的正确路径。
由于我没有 google cloud app credentials json 文件,所以我在我的测试演示中添加了一个 txt 文件来测试代码是否可以正常工作。
关于我的测试演示的更多细节,你可以引用下面的代码。
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);
}
}
结果(111为txt文件内容):
