我们有一个C#服务/ ASP.NET组合,我们需要定期将文件上传到Google云端硬盘。设计将是在ASP.NET项目中设置要连接的人,然后允许该服务上传文件。
我已经开始了该项目,使用nuget下载了所有库,在google中设置了我的clientid和secret,但是一切似乎都很简单,但是我的问题与我连接到别人的google drive实例有关?
我知道如果我们想连接到“约翰尼客户” google驱动器实例,我们需要连接到驱动器api并获得一个令牌,但是如何在C#中启动它?
提前感谢!
为了从C#应用程序访问共享驱动器,您可以使用服务帐户。此功能的想法是拥有一个帐户,您可以以编程方式登录该帐户并发出请求,而无需像使用“常规” OAuth2流那样显式允许该应用程序。您可以了解有关如何使用和创建服务帐户here的更多信息。
使用服务帐户的示例C#代码:
using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Plus.v1;
using Google.Apis.Plus.v1.Data;
using Google.Apis.Services;
namespace Google.Apis.Samples.PlusServiceAccount
{
/// <summary>
/// This sample demonstrates the simplest use case for a Service Account service.
/// The certificate needs to be downloaded from the Google API Console
/// <see cref="https://console.developers.google.com/">
/// "Create another client ID..." -> "Service Account" -> Download the certificate,
/// rename it as "key.p12" and add it to the project. Don't forget to change the Build action
/// to "Content" and the Copy to Output Directory to "Copy if newer".
/// </summary>
public class Program
{
// A known public activity.
private static String ACTIVITY_ID = "z12gtjhq3qn2xxl2o224exwiqruvtda0i";
public static void Main(string[] args)
{
Console.WriteLine("Plus API - Service Account");
Console.WriteLine("==========================");
String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE";
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { PlusService.Scope.PlusMe }
}.FromCertificate(certificate));
// Create the service.
var service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Plus API Sample",
});
Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();
Console.WriteLine(" Activity: " + activity.Object.Content);
Console.WriteLine(" Video: " + activity.Object.Attachments[0].Url);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
[获得凭据并创建DriveService
实例后,您只需要调用Files: create
端点即可将共享驱动器的根目录或其中的一个文件夹指定为所创建文件的父目录(请参见Files: create
规范)。共享驱动器。
例如:
"Request body"
您可以在此处了解有关服务帐户的更多信息:
var fileMetadata = new File();
fileMetadata.Name = "My File";
fileMetadata.Parents = new List<string> { "YOUR_SHARED_DRIVE_FOLDER_ID" };
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("your_folder/your_file",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream);
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
https://developers.google.com/identity/protocols/OAuth2ServiceAccount