首页 > 解决方案 > 尝试使用 Microsoft Graph 将用户添加到 AD 组时收到 400 错误请求

问题描述

我正在处理一个非常奇怪的问题。一年前我构建的代码运行良好,但现在不行了。

我正在尝试将用户添加到 AD 组,但收到 400 错误请求错误。我能做些什么来修复它?我应该切换到 ActiveDirectory 包的某个版本吗?

先感谢您。这是我的功能

public static async Task<string> AddGroupMember(string accessToken, string groupId, string memberId)
{
    var status = string.Empty;
    try
    {
        string endpoint = "https://graph.microsoft.com/v1.0/groups/" + groupId + "/members/$ref";
        string queryParameter = "";

        // pass body data 
        var keyOdataId = "@odata.id";
        var valueODataId = "https://graph.microsoft.com/v1.0/directoryObjects/" + memberId;

        var values = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>(keyOdataId, valueODataId)
        };
        var jsonData = $@"{{ ""{keyOdataId}"": ""{valueODataId}"" }}";
        var body = new StringContent(jsonData, Encoding.UTF8, "application/json");


        using (var client = new HttpClient())
        {
            using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint + queryParameter))
            {
                request.Content = body;
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                using (var response = await client.SendAsync(request))
                {
                    if (response.StatusCode == HttpStatusCode.NoContent)
                        status = "Member added to Group";
                    else
                        status = $"Unable to add Member to Group: {response.StatusCode}";
                }
            }
        }
    }
    catch (Exception ex)
    {
        status = $"Error adding Member to Group: {ex.Message}";
    }

    return status;
}

标签: microsoft-graph-api

解决方案


我找到了解决方案。我尝试添加组中已存在的用户。重复用户问题导致 400 Bad Request 错误


推荐阅读