使用Microsoft.Graph .NET SDK创建教育类时400错误的排查与解决
创建Microsoft Graph EducationClass时因ExternalSource字段触发400错误的解决办法
问题详情
用C#(.NET6)搭配版本5.15.0的Microsoft.Graph NuGet包创建教育类(EducationClass)时,只要请求体包含ExternalSource字段——不管设为sis还是manual——就会抛出400状态码的ODataError异常,错误信息为:"无法计算表达式,常见原因是尝试将lambda传递给委托"。
采用客户端凭证流(Client Credentials Flow)+客户端密钥认证,已给注册应用配置EduRoster.ReadWrite.All权限,其他Graph操作(如获取教育类、用户,创建组、团队)均能正常执行,即使用官方v1.0示例代码也会触发该错误。
排查后确认:移除ExternalSource字段即可成功创建教育类,且创建后的类该字段默认值为manual。目前正在尝试能否在创建完成后更新该字段。
相关代码示例
认证代码(无问题)
var scopes = new[] { "https://graph.microsoft.com/.default" }; var clientId = "YOUR_CLIENT_ID"; var tenantId = "YOUR_TENANT_ID"; var clientSecret = "YOUR_CLIENT_SECRET"; var options = new ClientSecretCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud, }; var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options); var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
触发报错的请求体代码
var requestBody = new EducationClass { OdataType = "#microsoft.graph.educationClass", DisplayName = "String", MailNickname = "String", Description = "String", CreatedBy = new IdentitySet { OdataType = "microsoft.graph.identitySet", }, ClassCode = "String", ExternalName = "String", ExternalId = "String", ExternalSource = EducationExternalSource.Sis, // 此字段导致400错误 ExternalSourceDetail = "String", Grade = "String", Term = new EducationTerm { OdataType = "microsoft.graph.educationTerm", }, }; var result = await graphClient.Education.Classes.PostAsync(requestBody);
修正后的请求体代码(移除ExternalSource字段)
var requestBody = new EducationClass { OdataType = "#microsoft.graph.educationClass", DisplayName = "String", MailNickname = "String", Description = "String", CreatedBy = new IdentitySet { OdataType = "microsoft.graph.identitySet", }, ClassCode = "String", ExternalName = "String", ExternalId = "String", ExternalSourceDetail = "String", Grade = "String", Term = new EducationTerm { OdataType = "microsoft.graph.educationTerm", }, }; var result = await graphClient.Education.Classes.PostAsync(requestBody);
后续尝试方向
当前已通过移除ExternalSource字段解决创建问题,接下来可尝试通过Graph的Patch请求,对已创建的EducationClass对象更新ExternalSource属性,验证是否支持事后修改该字段。
内容的提问来源于stack exchange,提问作者Chris AP
相关产品推荐
相关产品推荐

