使用C#调用Graph API发送共享邀请失败求助
解决Graph API发送共享邀请的400错误与过时方法警告
一、修复过时方法警告
Visual Studio提示的PostAsync方法已过时,需替换为PostAsInvitePostResponseAsync方法,修改后的调用方式如下:
// 替换原PostAsync调用逻辑 var response = await graphClient.Drives["{实际drive-id}"].Items["{实际driveItem-id}"].Invite.PostAsInvitePostResponseAsync(requestBody); var result = response.Value;
二、排查400错误的常见原因
400错误通常由参数格式或逻辑冲突导致,结合你的代码,重点检查以下几点:
1. 替换占位符
确保代码中的{drive-id}和{driveItem-id}已替换为实际的Drive ID和DriveItem ID,不能保留占位符字符串。
2. 修正过期时间
你代码中的ExpirationDateTime设置为2018-07-15T14:00:00.000Z,这是已过期的时间,Graph API不接受此类无效的共享邀请有效期,需修改为未来的ISO 8601格式时间,例如:
ExpirationDateTime = DateTime.UtcNow.AddDays(30).ToString("o")
3. 检查Password参数的使用场景
Password属性仅适用于OneDrive个人版,若你使用的是OneDrive商业版/教育版或SharePoint,添加该参数会直接触发400错误,需删除此参数:
// 移除Password配置行 // Password = "password123",
4. 验证收件人格式
确认Recipients中的邮箱地址ryan@contoso.com是有效且可接收邀请的邮箱,避免拼写错误。
5. 确认权限配置
确保你的应用已获得足够的权限,例如Files.ReadWrite.Shared、Sites.ReadWrite.All等,权限不足也可能引发参数验证类的400错误。
修改后的完整代码示例
var graphClient = new GraphServiceClient(requestAdapter); var requestBody = new Microsoft.Graph.Drives.Item.Items.Item.Invite.InvitePostRequestBody { Recipients = new List<DriveRecipient> { new DriveRecipient { Email = "ryan@contoso.com", }, }, Message = "Here's the file that we're collaborating on.", RequireSignIn = true, SendInvitation = true, Roles = new List<string> { "write", }, ExpirationDateTime = DateTime.UtcNow.AddDays(30).ToString("o"), }; var response = await graphClient.Drives["{实际drive-id}"].Items["{实际driveItem-id}"].Invite.PostAsInvitePostResponseAsync(requestBody); var result = response.Value;
内容的提问来源于stack exchange,提问作者Appguy1
相关产品推荐
相关产品推荐

