使用C# MIP SDK应用特定敏感度标签时遇AdhocProtectionRequiredException
解决MIP SDK应用特定敏感度标签时的AdhocProtectionRequiredException错误
问题原因
你遇到的AdhocProtectionRequiredException明确指出:目标标签要求临时(Ad-hoc)保护,但你没有提前设置保护参数。这类标签是管理员配置了自定义权限的保护策略,而非依赖默认模板保护,因此必须先通过SetProtection设置好保护规则,才能应用标签。
修改后的代码
public static void ChangeFileLabel(string filePath, string labelId) { using (var fileEngine = GetFileEngine()) { using (var fileHandler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(filePath, filePath, true)).Result) { // 1. 根据labelId获取目标标签对象(原代码中label变量未定义,补充此步骤) var targetLabel = fileEngine.GetLabels().FirstOrDefault(l => l.Id == labelId); if (targetLabel == null) { throw new ArgumentException($"无法找到ID为{labelId}的标签"); } // 2. 判断标签是否需要临时保护,提前设置保护参数 if (targetLabel.Protection != null && targetLabel.Protection.Type == ProtectionType.Adhoc) { // 构建临时保护配置:指定允许访问的用户/组及权限 var adhocSettings = new AdhocProtectionSettings { // 示例:添加允许访问的用户(应用程序身份下需确保用户ID或UPN正确) Users = new List<UserRights> { new UserRights("user@contoso.com", new List<Permission> { Permission.View, Permission.Edit }) }, // 可选:设置是否允许离线访问、过期时间等 AllowOfflineAccess = OfflineAccess.Unlimited, }; // 先设置临时保护 fileHandler.SetProtection(adhocSettings); } // 3. 设置标签及选项 LabelingOptions labelingOptions = new LabelingOptions() { AssignmentMethod = AssignmentMethod.Standard, IsDowngradeJustified = true, JustificationMessage = "test" }; fileHandler.SetLabel(targetLabel, labelingOptions, new ProtectionSettings()); // 4. 提交更改到文件 using (var memoryStream = new MemoryStream()) { Task.Run(async () => await fileHandler.CommitAsync(memoryStream)).GetAwaiter().GetResult(); memoryStream.Position = 0; using (var outputFileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { memoryStream.CopyTo(outputFileStream); } } } } }
关键说明
- 标签获取:原代码中直接使用
label变量但未定义,补充了通过labelId从引擎获取标签的逻辑,这是必要步骤。 - 保护判断:通过
targetLabel.Protection.Type判断是否为临时保护,避免对不需要的标签执行多余操作。 - AdhocProtectionSettings配置:
Users列表需指定有权限访问该文件的用户/组,每个用户对应一组权限(如View、Edit、Print等)。- 应用程序身份验证下,确保服务主体拥有管理保护策略的权限,并且指定的用户ID/UPN在Azure AD中有效。
- 调用顺序:必须先调用
SetProtection完成保护配置,再调用SetLabel应用标签,顺序不能颠倒。
注意事项
- 不同管理员创建的标签保护配置差异较大,建议在代码中增加异常捕获,针对不同标签类型做分支处理。
- 如果标签的临时保护有固定的权限模板,可以提前在Azure AD中配置,再通过模板ID调用
SetProtection,无需手动指定每个用户权限。 - 应用程序身份需要在Azure AD中授予
InformationProtectionPolicy.Read和InformationProtectionProtection.ReadWrite等相关权限。
内容的提问来源于stack exchange,提问作者John Park
相关产品推荐
相关产品推荐

