首页 > 解决方案 > 为什么我无法将文件权限更新给所有者?(Google.Apis.Drive.v3)

问题描述

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

我读过官方文件说“角色”字段是可写的。
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] 错误 [消息[资源主体包括不可直接写入的字段。] 位置 [ - ] 原因 [fieldNotWritable] 域 [全局]]


(更新)

我改变了我的代码

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#.netgoogle-apigoogle-drive-apigoogle-api-dotnet-client

解决方案


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

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

使用 update 方法时,只允许权限的以下属性:expireTimerole

请参阅:权限:更新请求正文部分。

你可以试试这个:

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;

推荐阅读