【问题标题】:Why I can not Update File Permission to owner? (Google.Apis.Drive.v3)为什么我无法将文件权限更新给所有者? (Google.Apis.Drive.v3)
【发布时间】:2020-02-17 06:04:11
【问题描述】:

我用服务帐户上传文件,然后我想将所有者权限转移到我自己的帐户,但它总是抛出一个异常“资源体包含不可直接写入的字段。”

我阅读官方文档说“角色”字段是可写的。
https://developers.google.com/drive/api/v2/reference/permissions/update

我需要在哪里更正?

我的 api 版本是 Google APIs Drive v3

这是我在谷歌开发者那里复制的示例代码

 try
        {
            // First retrieve the permission from the API.
            Permission permission = service.Permissions.Get(fileId, permissionId).Execute();
            permission.Role = newRole;
            return service.Permissions.Update(permission, fileId, permissionId).Execute();
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }

        return null;

在 Execute() 之后,我收到此错误消息。

Google.Apis.Requests.RequestError 资源主体包含不可直接写入的字段。 [403] 错误 [消息[资源主体包括不可直接写入的字段。] Location[ - ] Reason[fieldNotWritable] Domain[global]]


(更新)

我改变了我的代码

public Permission ModifyPermission(DriveService service, string fileId, string permissionId, string newRole)
    {
        try
        {
            if (String.IsNullOrEmpty(newRole)) return null;

            var permission = new Permission
            {
                Role = newRole
            };

            var request = service.Permissions.Update(permission, fileId, permissionId);

            if(newRole == "owner") request.TransferOwnership = true;

            return request.Execute();
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }

        return null;
    }

然后它抛出另一个异常。

Google.Apis.Requests.RequestError 用户对此文件没有足够的权限。 [403] 错误 [ 消息[用户对此文件没有足够的权限。]位置[-]原因[insufficientFilePermissions]域[全局] ]


该文件是通过 JSON 格式的服务帐户凭据上传的。而且我更新权限与上传的凭据相同。

我错过了什么?

【问题讨论】:

  • 插入新权限不要更新。

标签: c# .net google-api google-drive-api google-api-dotnet-client


【解决方案1】:

您提供的权限对象填充的属性多于驱动 api 接受的属性。

例如,KindType 属性是在使用 get 方法检索权限时填充的。

使用更新方法时,仅允许权限的以下属性:expirationTimerole

参见:Permissions: update请求正文部分。

你可以试试这个:

try
{
    var permission = new Permission
    {
        Role = newRole
    };
    return service.Permissions.Update(permission, fileId, permissionId).Execute();
}
catch (Exception e)
{
    Console.WriteLine("An error occurred: " + e.Message);
}

return null;

【讨论】:

  • 感谢您的回复,我尝试了您的建议。它可以工作,但例外是“用户对此文件没有足够的权限”。我通过服务账号JSON凭证调用api,应该有修改权限。
  • 用户对文件有写权限吗?请参阅here 了解一些可能有用的附加错误信息。
  • 是的,该文件有 2 个权限。一个是服务帐户,另一个是权限字段角色为“作家”的用户。
猜你喜欢
  • 2013-04-08
  • 2014-08-11
  • 2016-02-04
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 2015-11-02
相关资源
最近更新 更多