我们测试了Google云端硬盘的演示代码(用于控制台应用程序),这是正确的,之后我们尝试将其实现为目前在localhost上托管的Web应用程序。该应用程序给了我们这个例外:
Google.Apis.Auth.dll中出现“System.InvalidOperationException”类型的异常但未在用户代码中处理 信息:至少应有一个客户机密(安装或Web) 设置
我们尝试运行的代码是:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
在此之前我们已经放置了刷新令牌来获取访问令牌。我们也不知道如何处理这个访问令牌存储在字符串变量中。
我们试图让它无法访问,我们使用google playground获取第一个刷新令牌。
请帮助我们,我们正努力在过去7天内完成任务,但没有成功。
答案 0 :(得分:3)
服务帐户代码:
string[] scopes = new string[] {DriveService.Scope.Drive}; // Full access
var keyFilePath = @"c:\file.p12" ; // Downloaded from https://console.developers.google.com
var serviceAccountEmail = "xx@developer.gserviceaccount.com"; // found https://console.developers.google.com
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) {
Scopes = scopes}.FromCertificate(certificate));
代码从Google Drive Authentication C#中删除,这也包含了使用Oauth2
的示例上传文件
/// <summary>
/// Uploads a file
/// Documentation: https://developers.google.com/drive/v2/reference/files/insert
/// </summary>
/// <param name="_service">a Valid authenticated DriveService</param>
/// <param name="_uploadFile">path to the file to upload</param>
/// <param name="_parent">Collection of parent folders which contain this file.
/// Setting this field will put the file in all of the provided folders. root folder.</param>
/// <returns>If upload succeeded returns the File resource of the uploaded file
/// If the upload fails returns null</returns>
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
//request.Convert = true; // uncomment this line if you want files to be converted to Drive format
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
代码摘自DaimtoGoogleDriveHelper.cs
提示强>
使用服务帐户要记住的是,它不是您,它是一个虚拟用户帐户。服务帐户拥有自己的Google云端硬盘帐户,因此向其上传文件将上传到其帐户而不是您的帐户。您可以做的是将服务帐户电子邮件地址作为用户添加到您的个人Google云端硬盘帐户中的文件夹中,从而为其提供写入权限。然后,这将允许服务帐户将文件上传到您的个人Google云端硬盘帐户。请记住,在上传后授予自己对文件的权限,以便文件的所有者将成为服务帐户。 Google Drive api中目前存在一个错误,您必须在上传文件之后修补文件的权限,而您在上传文件时只需执行两个步骤即可。 (去过那里)
可以在GitHub
上找到Google云端硬盘示例项目