有人有一个如何将 Google.Apis.Auth.OAuth 与 C# Webforms 结合使用的简单示例吗? 我只能找到 MVC 的。
最佳答案
我花了一段时间将原始示例转换为控制台应用程序 - 它的真正目的是展示您的应用程序如何访问用户自己的 Google 表格。
https://developers.google.com/sheets/api/quickstart/dotnet
有一个基于 MVC 的示例 - 它不太适合 Web 表单 - 然而,这又适用于网站访问任何用户数据的情况
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-aspnet-mvc
因此,这两个过程的一部分 - 是您被发送到 Google 的 API 以授予对用户数据的访问权限,例如访问您拥有的 Google 表格。授予访问权限后,它将返回到您指定的返回 URL。
控制台示例打开浏览器以授予访问位。
一旦您授予访问权限,就会保存一个文件,该文件存储此权限,并且不需要再次请求。
我将控制台应用程序代码转换为在 Web 表单中运行,但这需要我复制凭据文件(我使用控制台应用程序示例生成的)。无法生成凭据文件,因为它试图让 IIS 启动浏览器来获取 IIS 用户无权执行的权限(并且无论如何都无法在生产环境中工作)。如果您已将该文件复制到 IIS 可以查看的某个位置,它仍然可以工作(如果凭据文件存在,它会跳过打开浏览器来获取权限)。
这是我的示例(网络表单的代码隐藏):
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Sheets.v4
Imports Google.Apis.Sheets.v4.Data
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports System.Collections.Generic
Imports System.Threading
Private Sub btnImportData_Click(sender As Object, e As EventArgs) Handles btnImportData.Click
Dim ApplicationName As String = "Google Sheets API .NET Quickstart"
'Dim credPath As String = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
'credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
Dim credPath As String = Server.MapPath("~/YourPathToCredentials/google-api-credentials")
Dim CS As New ClientSecrets With {
.ClientId = "-- YOUR CLIENT ID --",
.ClientSecret = "-- YOUR CLIENT SECRET --"
}
'Dim Scopes As String() = {SheetsService.Scope.SpreadsheetsReadonly}
Dim Scopes As IEnumerable(Of String) = {SheetsService.Scope.Drive}
'Dim DataStore = New FileDataStore("Drive.Api.Auth.Store")
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(CS, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Diagnostics.Debug.WriteLine("Credential file saved to: " & credPath)
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
'Glossary Spreadsheet used as data repository for Glossary BETA Google Forms prototype
Dim spreadsheetId As String = "-- YOUR GOOGLE SHEET ID --"
Dim range As String = "Form responses 1!A2:G"
Dim request As SpreadsheetsResource.ValuesResource.GetRequest = service.Spreadsheets.Values.[Get](spreadsheetId, range)
Dim response As ValueRange = request.Execute()
Dim values As IList(Of IList(Of Object)) = response.Values
If values IsNot Nothing AndAlso values.Count > 0 Then
Diagnostics.Debug.WriteLine("Category, Term, Definition")
For Each row In values
Diagnostics.Debug.WriteLine("{0}, {1}, {2}", row(3), row(1), row(2))
Next
Else
Diagnostics.Debug.WriteLine("No data found.")
End If
End Sub
一种更相关且更简单的方法是一种完全不同的类型,它专为服务器到服务器通信而设计,即 Google API 的 Webform 代码隐藏。
为此,您需要一个“服务帐户” - 这些凭据是在 api 后端创建的,然后可以由代码中的 Web 应用程序使用 - 这正是我正在寻找的用例(始终相同的数据存储) Google 表格中归我所有)。
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service-account
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
这是我使用 Google 服务帐户的示例。
注意 - 我在 Google API 控制台上创建了一个服务帐户 - 这会为该后台帐户生成一个电子邮件地址 - 我必须为我感兴趣的工作表授予此电子邮件的权限。Google 上的代码示例是对于较旧的 P12 格式 - 而 API 控制台建议使用较新的 JSON 格式。我的示例代码已修改为使用更现代的 JSON 格式。创建服务帐户时,它会为您提供一个要下载的文件请确保将副本安全保存在某个位置,因为您将无法重新生成该文件。如果您这样做,也不是世界末日,但您将无法再次使用该帐户,您必须创建一个新帐户并授予该帐户权限。
Imports System.Data
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Sheets.v4
Imports Google.Apis.Sheets.v4.Data
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports System.Collections.Generic
Imports System.Threading
Imports System.IO
Public Sub ImportGlossaryGoogleSheetData_ServiceAccount()
Diagnostics.Debug.WriteLine("=====================================")
Diagnostics.Debug.WriteLine("Import Glossary using Service Account")
Diagnostics.Debug.WriteLine("=====================================")
Dim credPath As String = Server.MapPath("~/YourPathToCredentials/google-api-credentials/credentialfile.json")
Dim credential As ServiceAccountCredential
Using stream As New FileStream(credPath, FileMode.Open, FileAccess.Read, FileShare.Read)
credential = GoogleCredential.FromStream(stream).CreateScoped({SheetsService.Scope.Drive}).UnderlyingCredential
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "YOUR APP NAME"
})
'Glossary Spreadsheet used as data repository for Glossary BETA Google Forms prototype
Dim spreadsheetId As String = "-- YOUR GOOGLE SHEET ID --"
Dim range As String = "Form responses 1!A2:G"
Dim request As SpreadsheetsResource.ValuesResource.GetRequest = service.Spreadsheets.Values.[Get](spreadsheetId, range)
Dim response As ValueRange = request.Execute()
Dim values As IList(Of IList(Of Object)) = response.Values
If values IsNot Nothing AndAlso values.Count > 0 Then
Diagnostics.Debug.WriteLine("Category, Term, Definition")
For Each row In values
Diagnostics.Debug.WriteLine("{0}, {1}, {2}", row(3), row(1), row(2))
Next
Else
Diagnostics.Debug.WriteLine("No data found.")
End If
End Sub
我希望这能解释我对谷歌提供的不同方法的发现:
OAuth - 一种通用方法,允许您的代码有权查看 用户数据,例如您的网站查看用户 Google 中的数据 表格。
服务帐户 - 服务器到服务器访问 Google API - 例如你的 网站使用 Google API 查看特定数据,即硬编码为 查看您拥有的数据并在 Google 中生成凭据 API后端。
关于.net - 用于 Web 表单的 Google.Apis.Auth.OAuth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22911691/