Graph REST AddMember to Group - Bad Request

允我心安 提交于 2019-12-24 01:24:59

问题


I am attempting to add members to a group. I am able to list all groups in my org, get user by email, get all users and I can even remove a Member from a group but I cannot add one - The error returned is 400 Bad Request.

Here is the function which is the same function signature as those that work: (I do have the accesstoken, valid group id and a valid member id)

I have confirmed the body data looks correct at least as far as I can see from the example in the docs.

Not sure what else I can add to make things clearer, ask and I'll update

public async Task<string> AddGroupMember(string accessToken, string groupId, string memberId)
{
    var status = string.Empty;
    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 body = new FormUrlEncodedContent(values);

    try
    {
        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;
}

Thanks for any help that anyone can offer - this is the last call I have to make then home free


回答1:


Found the issue for any who care to know for the future:

var body = new FormUrl... my code was incorrect, what's needed is a simple json string changed to this UPDATED:

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

I would normally put the values in a class but this is for proof of concept and the json key needs to look exactly like this @odata.id




回答2:


Clarifying what is happening here:

The request body for this call should be JSON encoded (application/json). The FormUrlEncodedContent method returns your dictionary as Form encoded (application/x-www-form-urlencoded).

You can write the JSON by hand (like you have so far) but a better solution would be to leverage Json.NET. This will let you encode the dictionary in much the same way you were with FormUrlEncodedContent:

var values = new Dictionary<string, string>
    {
       { keyOdataId, valueODataId}
    };
var body = JsonConvert.SerializeObject(values);

If you're going to be doing a lot of work with Microsoft Graph, I would highly recommend switching to the Microsoft Graph .NET SDK.

You're method here would be far simpler using the SDK:

public async Task<string> AddGroupMember(string groupId, string memberId)
{
    GraphServiceClient graphClient = AuthenticationHelper.GetAuthenticatedClient();
    User userToAdd = new User { Id = memberId };
    await graphClient.Groups[groupId].Members.References.Request().AddAsync(userToAdd);
}


来源:https://stackoverflow.com/questions/46573102/graph-rest-addmember-to-group-bad-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!