在Net Core中使用Microsoft Graph Api将用户添加为组成员

时间:2020-06-19 17:32:17

标签: c# asp.net-core-mvc microsoft-graph-api odata azure-ad-graph-api

在我的项目中,我正在Net Core 3.0项目中使用Microsoft Graph Api连接到Azure Intune并添加组和用户。当添加具有成员的组时,图api需要用户的json表示形式,例如((documentation):

var group = new Group
{
    // other properties omitted
    AdditionalData = new Dictionary<string, object>()
    {
        {"owners@odata.bind", "[\"https://graph.microsoft.com/v1.0/users/26be1845-4119-4801-a799-aea79d09f1a2\"]"},
        {"members@odata.bind", "[\"https://graph.microsoft.com/v1.0/users/ff7cb387-6688-423c-8188-3da9532a73cc\",\"https://graph.microsoft.com/v1.0/users/69456242-0067-49d3-ba96-9de6f2728e14\"]"}
    }
};

简要说明: 我从文档中尝试了上面的代码,用想要添加的用户替换了Guid,但这也不起作用,给了我同样的错误消息。 结束编辑。

我该如何动态地在字典中添加成员,例如从用户ID的数组中添加成员?他们似乎使用转义字符,并且使用JsonConvert.SerializeObject(arrayObjectWithIds)似乎不起作用,因为我从图形Api返回了格式不正确的OData字段:Invalid URL format specified in @odata.bind for members

我所拥有的:

string[] memberIds = new string[] { "https://graph.microsoft.com/v1.0/users/123", "https://graph.microsoft.com/v1.0/users/456", "https://graph.microsoft.com/v1.0/users/789" };
string json = JsonConvert.SerializeObject(memberIds);

newGroup.AdditionalData = new Dictionary<string, object>()
{
    {"members@odata.bind", json }
};

// Send it off and get Invalid URL format specified in @odata.bind for members error

这是我的json,因为它目前已附加到字典中:

["https://graph.microsoft.com/v1.0/users/123\"","https://graph.microsoft.com/v1.0/users/456\"","https://graph.microsoft.com/v1.0/users/789\""]

将成员uri放入字典对象的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

问题是由代码中的转义字符\"引起的,我测试了文档中的相同代码,并且还看到了相同的错误消息Invalid URL format specified in @odata.bind for members。因此,我将代码修改如下:

var additionalData = new Dictionary<string, object>()
    {
        {"owners@odata.bind", new List<string>()},
        {"members@odata.bind", new List<string>()}
    };
(additionalData["members@odata.bind"] as List<string>).Add("https://graph.microsoft.com/v1.0/users/xxxxx");
(additionalData["owners@odata.bind"] as List<string>).Add("https://graph.microsoft.com/v1.0/users/xxxxx");

var group = new Group
{
    Description = "Group with designated owner and members",
    DisplayName = "huryNewGroup",
    GroupTypes = new List<String>()
    {
        "Unified"
    },
    MailEnabled = true,
    MailNickname = "operations2019",
    SecurityEnabled = false,
    AdditionalData = additionalData
};

运行代码,我成功地创建了包含成员的组。

顺便说一句,我们可能会遇到权限问题。刚开始,我只为应用程序添加了权限Group.ReadWrite.All,但是它表明我在运行代码时没有权限。然后我添加了其他权限Directory.ReadWrite.All, Directory.AccessAsUser.All,它工作正常。(据我所知,Group权限存在一些小问题,因此,最好添加其他Directory权限)

希望有帮助〜