admin管理员组文章数量:1122846
I have a little tool which creates and manages User for me (local Active Directory -> Sync to Azure AD). I can assigne a User to multiple Groups (Local and Cloud) and this worked just fine with Graph api SDK < V5. I Used to do the following:
var directoryObject = new DirectoryObject
{
Id = userid
};
try
{
foreach (String i in groupids)
{
await graphClient.Groups[i].Members.References
.Request()
.AddAsync(directoryObject);
}
}
Now with the new Update to Graph API SDK V5 a lot has changed and i got everythink working except this step. To do it for SDK v5 i do the following:
var requestbody = new ReferenceCreate
{
OdataId = graphClient.DirectoryObjects[userid].ToGetRequestInformation().URI.ToString(),
};
foreach (String i in groupids)
{
await graphClient.Groups[i].Members.Ref.PostAsync(requestbody);
}
This always works for ONE! Group. When the Second Group is set, I get the following Error:
an unexpected 'end of input' node was found when reading from the json reader
So i guessed i try doing it in Bulk:
var requestbody = new ReferenceCreate
{
OdataId = graphClient.DirectoryObjects[userid].ToGetRequestInformation().URI.ToString(),
};
try
{
var batchRequestContent = new BatchRequestContentCollection(graphClient);
foreach (String i in groupids)
{
var requestStepId = await batchRequestContent.AddBatchRequestStepAsync(graphClient.Groups[i].Members.Ref.ToPostRequestInformation(requestbody));
}
var batchResponse = await graphClient.Batch.PostAsync(batchRequestContent);
And again, even with the Bulk Method, the User is only added to ONE Group.
If i look inside the Responsemessage from the Failing step of the Bulk i got:
Bad Request
yet if i try the same Update with Graph Explorer everything works fine.
What is my error here? The IDs are correct, the User-ID is correct, if i switch the Groups in the List the problem is the same, first Group is set, other Groups get ignored. Is there an easy way to add ONE user to Multiple Groups in Graph API SDK v5? Or am i just missing a hughe Point?
I have a little tool which creates and manages User for me (local Active Directory -> Sync to Azure AD). I can assigne a User to multiple Groups (Local and Cloud) and this worked just fine with Graph api SDK < V5. I Used to do the following:
var directoryObject = new DirectoryObject
{
Id = userid
};
try
{
foreach (String i in groupids)
{
await graphClient.Groups[i].Members.References
.Request()
.AddAsync(directoryObject);
}
}
Now with the new Update to Graph API SDK V5 a lot has changed and i got everythink working except this step. To do it for SDK v5 i do the following:
var requestbody = new ReferenceCreate
{
OdataId = graphClient.DirectoryObjects[userid].ToGetRequestInformation().URI.ToString(),
};
foreach (String i in groupids)
{
await graphClient.Groups[i].Members.Ref.PostAsync(requestbody);
}
This always works for ONE! Group. When the Second Group is set, I get the following Error:
an unexpected 'end of input' node was found when reading from the json reader
So i guessed i try doing it in Bulk:
var requestbody = new ReferenceCreate
{
OdataId = graphClient.DirectoryObjects[userid].ToGetRequestInformation().URI.ToString(),
};
try
{
var batchRequestContent = new BatchRequestContentCollection(graphClient);
foreach (String i in groupids)
{
var requestStepId = await batchRequestContent.AddBatchRequestStepAsync(graphClient.Groups[i].Members.Ref.ToPostRequestInformation(requestbody));
}
var batchResponse = await graphClient.Batch.PostAsync(batchRequestContent);
And again, even with the Bulk Method, the User is only added to ONE Group.
If i look inside the Responsemessage from the Failing step of the Bulk i got:
Bad Request
yet if i try the same Update with Graph Explorer everything works fine.
What is my error here? The IDs are correct, the User-ID is correct, if i switch the Groups in the List the problem is the same, first Group is set, other Groups get ignored. Is there an easy way to add ONE user to Multiple Groups in Graph API SDK v5? Or am i just missing a hughe Point?
Share Improve this question asked Nov 21, 2024 at 19:45 Angl0rAngl0r 173 bronze badges 1- Could you include what authentication flow you are using? client credentials? – Sridevi Commented Nov 22, 2024 at 3:51
2 Answers
Reset to default 1Initially, I registered one application and granted GroupMember.ReadWrite.All permission of Application type as below:
To add user to multiple groups in Microsoft Graph SDK v5, you can make use of below sample code:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Models.ODataErrors;
class Program
{
static async Task Main(string[] args)
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenantId";
var clientId = "appId";
var clientSecret = "secret";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
string userId = "userId"; // Replace with your user ID
var groupIds = new List<string> { "groupId1", "groupId2", "groupId3" }; // Replace with your group IDs
try
{
// Adding user to multiple groups
foreach (string groupId in groupIds)
{
var requestBody = new ReferenceCreate
{
OdataId = $"https://graph.microsoft.com/v1.0/directoryObjects/{userId}"
};
try
{
await graphClient.Groups[groupId].Members.Ref.PostAsync(requestBody);
Console.WriteLine($"Successfully added user {userId} to group {groupId}");
}
catch (ODataError odataError)
{
Console.WriteLine($"Failed to add user {userId} to group {groupId}: {odataError.Error.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error adding user {userId} to group {groupId}: {ex.Message}");
}
}
}
catch (Exception exception)
{
Console.WriteLine($"{exception.GetType().FullName}: {exception.Message}");
}
}
}
Response:
To confirm that, I checked the same in Portal where user added to multiple groups successfully as below:
The issue is with ReferenceCreate
, you need to create a new instance of ReferenceCreate
for each group. The ReferenceCreate
and other Graph SDK models implement the backing store that tracks changes in properties. Once the instance of ReferenceCreate
is serialized to the body of the first request, it's not serialized in other requests.
foreach (var groupId in groupIds)
{
var referenceCreate = new ReferenceCreate
{
OdataId = $"https://graph.microsoft.com/v1.0/directoryObjects/${userId}"
};
var request = graphClient.Groups[groupId].Members.Ref.ToPostRequestInformation(referenceCreate);
await batchRequestContent.AddBatchRequestStepAsync(request);
}
var returnedResponse = await graphClient.Batch.PostAsync(batchRequestContent);
本文标签: netC Graph api SDK V5Add User to multiple GroupsStack Overflow
版权声明:本文标题:.net - C# Graph api SDK V5 - Add User to multiple Groups - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736307597a1933368.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论