C# .net MVC, set path to Google Application Creden

2020-08-15 01:19发布

问题:

I've just got this Google Sample Project to work on my VS2015,

However, after I published to "IIS" and host it, when I opened the link, the web page kept showing this message as the picture showed

I added the key to the web.config, but still doesn't work, just wondering if anyone had done this before, I really need help, thank you!

Edit: Here is my code

Web.Config

  <appSettings>
<!-- Set to your Google project id as shown on the Google Developers Console -->
<add key="GoogleCloudSamples:ProjectId" value="gdtest-1332" />
<add key="GOOGLE_APPLICATION_CREDENTIALS" value="D:\ProjectCloud\gdtest-12323.json" />
<!--
Set to either mysql or datastore.
If using mysql, update the connectionString far below, and then run Update-Database in the
Package Manager Console.
-->
<add key="GoogleCloudSamples:BookStore" value="datastore" />
<!-- Set to your Google Cloud Storage bucket -->
<add key="GoogleCloudSamples:BucketName" value="cloudstoragetestbillez" />
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

回答1:

Programmatically set an environment variable at runtime as such:

string credential_path = @"C:\..\key.json";
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);

I'm not an expert with IIS but it won't seem to pick up on environment variable set in your desktop environment.



回答2:

Restarting the Visual Studio 2017 did it for me for Console Application.

Console.WriteLine(System.Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"));



回答3:

From google documention it seems it is env var and not web.config.

If you are using a service account credential, set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path to the JSON credential file you downloaded.



回答4:

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH_JSON]

You don´t need setting credentials on code



回答5:

Google says:

After creating a service account, you have two choices for providing the credentials to your application. You can either set the GOOGLE_APPLICATION_CREDENTIALS environment variable explicitly, or you can pass the path to the service account key in code.