Microsoft Graph Service Client PATCH自定义安全属性失败排查
问题:Graph Explorer PATCH自定义安全属性成功,但C#代码报错"Invalid property 'SalesforceAccountId'"
问题场景
使用Microsoft Graph Service Client的C#代码为用户PATCH自定义安全属性时,Graph Explorer中对应的HTTP请求可成功执行,但相同逻辑的C#代码抛出Invalid property 'SalesforceAccountId'错误。代码仅修改了官方示例中的属性集、属性名和值,逻辑与示例一致。
官方示例代码
var requestBody = new User { CustomSecurityAttributes = new CustomSecurityAttributeValue { AdditionalData = new Dictionary<string, object> { { "Engineering" , new { OdataType = "#Microsoft.DirectoryServices.CustomSecurityAttributeValue", ProjectDate = "2022-10-01", } }, }, }, }; var result = await graphClient.Users["{user-id}"].PatchAsync(requestBody);
官方示例对应的HTTP请求
PATCH https://graph.microsoft.com/v1.0/users/{id} Content-type: application/json { "customSecurityAttributes": { "Engineering": { "@odata.type":"#Microsoft.DirectoryServices.CustomSecurityAttributeValue", "ProjectDate":"2022-10-01" } } }
用户代码
var requestBody = new User { CustomSecurityAttributes = new CustomSecurityAttributeValue { AdditionalData = new Dictionary<string, object> { { "SalesforceAccountId" , new { ODataType = "#Microsoft.DirectoryServices.CustomSecurityAttributeValue", Id = accountId, } }, }, }, }; await _graphServiceClient.Users[userId].PatchAsync(requestBody);
错误信息
Microsoft.Graph.Beta.Models.ODataErrors.ODataError: Invalid property 'SalesforceAccountId'. at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.ThrowIfFailedResponse(HttpResponseMessage response, Dictionary`2 errorMapping, Activity activityForAttributes, CancellationToken cancellationToken) ...(省略后续栈信息)
原因分析
核心问题是CustomSecurityAttributes的AdditionalData字典结构错误:
- 官方示例中,AdditionalData的键是属性集(AttributeSet)名称(如
Engineering),值是包含该属性集下具体属性的对象; - 你的代码把属性名
SalesforceAccountId直接作为了AdditionalData的键,相当于把属性名错误当成了属性集名称,导致Graph API无法识别这个不存在的"属性集",因此抛出无效属性的错误。
解决方法
- 先确认你的自定义安全属性
SalesforceAccountId所属的属性集名称(可在Azure AD的自定义安全属性配置页面查看); - 调整AdditionalData的结构,外层字典键为属性集名称,内层对象包含具体属性名和值:
修正后的代码示例
var requestBody = new User { CustomSecurityAttributes = new CustomSecurityAttributeValue { AdditionalData = new Dictionary<string, object> { { // 替换为你的属性集名称,比如"Salesforce" "Salesforce" , new { ODataType = "#Microsoft.DirectoryServices.CustomSecurityAttributeValue", SalesforceAccountId = accountId, // 这里是属性名和对应值 } }, }, }, }; await _graphServiceClient.Users[userId].PatchAsync(requestBody);
调整后,生成的HTTP请求结构会和Graph Explorer中成功的请求一致:外层是属性集,内层是该属性集下的具体属性,Graph API就能正确识别并处理。
内容的提问来源于stack exchange,提问作者Scarecrow Krone
相关产品推荐
相关产品推荐

