I am using .NET Core 3.1 and I am trying to connect to the Google's Indexing API by presenting a private key. I have looked at things like: Example of Google Indexing API Batch Request using .NET and https://hamidmosalla.com/2019/12/07/using-google-indexing-api-with-google-api-client-library-for-net/
Here is my code:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Indexing.v3;
using Google.Apis.Indexing.v3.Data;
using Microsoft.Extensions.Hosting.Internal;
public static class MyClassDownloader {
public static GoogleCredential GetGoogleCredential()
{
string path = HostingEnvironment.MapPath("/PrivateKey/myprivatekey.json");
GoogleCredential credential;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(new[] { "https://www.googleapis.com/auth/indexing" });
}
return credential;
}
}
However, I am getting an error on the line regarding MapPath
:
'HostingEnvironment' does not contain a definition for 'MapPath'
I have tried looking into IHostingEnvironment
, after which I learned it was deprecated for IWebHostEnvironment
. How do I get the proper physical path for my JSON file regardless of if I am in development or production?
I'd change
MyClassDownloader
to not be static and add a constructor that takesIWebHostEnvironment
as a parameter which would be saved in a variable insideMyClassDownloader
. Then,MyClassDownloader
needs to be registered inStartup.ConfigureServices()
. Finally everywhereMyClassDownloader.GetGoogleCredential()
is called (e.g. in controllers), an instance ofMyClassDownloader
needs to be available. This instance is made available through injecting it into the using class' (e.g. the controller) constructor.Example (I did not test that code):