在 windows 服务中使用 Gmail API
Using the Gmail API inside a windows service
我做了一项服务,可以从我的电子邮件中读取新电子邮件并对其进行操作,它应该 运行ning 作为一项 windows 服务,但问题是你第一次运行 应用提示 google 访问验证,仅一次。我可以 运行 它作为控制台应用程序一次,进行身份验证,然后 运行 它无限次而无需身份验证,但是当 运行 将项目作为 windows 服务时该应用程序无法运行,因为没有提示 window 授权访问,有人有想法或资源可以帮助我吗?
编辑***
我可以看到在第一次身份验证后它创建了 token.json & 然后应用程序使用它在没有提示的情况下进行身份验证,为什么服务无法读取它?
这是它的样子 :
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath ,false )).Result;
}
FileDataStore 首先在 运行 上创建了 token.json 文件夹 + 文件,然后重新使用它,所以我不知道为什么应用 运行ning 作为 windows 服务无法像在控制台应用程序上那样从那里读取它。
Windows 服务在启动时读取 app.config 文件。因此,如果您稍后更改 app.config 中的某些值,您要么需要重新启动服务,要么可以使用此代码刷新包含您的令牌的部分,然后读取它。
参见:original answer from jdigaetano
ConfigurationManager.RefreshSection("appSettings")
sValue = ConfigurationManager.AppSettings(name)
您可以在 documentation 中找到有关 RefreshSection 的更多信息。
您可以在 appSettings 中创建新密钥
<appSettings>
<add key="path" value="" />
</appSettings>
然后如果你想保存你的token.json配置文件的路径,你可以这样做
Configuration config = ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["path"].Value = "pathToTokenJson";
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
请注意,您需要添加对 System.Configuration
的引用
我做了一项服务,可以从我的电子邮件中读取新电子邮件并对其进行操作,它应该 运行ning 作为一项 windows 服务,但问题是你第一次运行 应用提示 google 访问验证,仅一次。我可以 运行 它作为控制台应用程序一次,进行身份验证,然后 运行 它无限次而无需身份验证,但是当 运行 将项目作为 windows 服务时该应用程序无法运行,因为没有提示 window 授权访问,有人有想法或资源可以帮助我吗?
编辑***
我可以看到在第一次身份验证后它创建了 token.json & 然后应用程序使用它在没有提示的情况下进行身份验证,为什么服务无法读取它?
这是它的样子 :
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath ,false )).Result;
}
FileDataStore 首先在 运行 上创建了 token.json 文件夹 + 文件,然后重新使用它,所以我不知道为什么应用 运行ning 作为 windows 服务无法像在控制台应用程序上那样从那里读取它。
Windows 服务在启动时读取 app.config 文件。因此,如果您稍后更改 app.config 中的某些值,您要么需要重新启动服务,要么可以使用此代码刷新包含您的令牌的部分,然后读取它。
参见:original answer from jdigaetano
ConfigurationManager.RefreshSection("appSettings")
sValue = ConfigurationManager.AppSettings(name)
您可以在 documentation 中找到有关 RefreshSection 的更多信息。
您可以在 appSettings 中创建新密钥
<appSettings>
<add key="path" value="" />
</appSettings>
然后如果你想保存你的token.json配置文件的路径,你可以这样做
Configuration config = ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["path"].Value = "pathToTokenJson";
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
请注意,您需要添加对 System.Configuration