创建组Microsoft Graph

时间:2016-07-04 08:41:24

标签: c# rest azure office365 microsoft-graph

我对Microsoft Graph API有疑问。 我尝试在C#程序中通过REST API调用创建一个组,并且我一直收到“未授权”错误。

  • 我创建了一个Azure Web App。
  • 我已将GraphAPI的权限设置为:“读取并写入所有组”
  • 我有clientID和clientSecret
  • 我有tenantID
  • 我从GetTokenForApplication方法获得了一个工作令牌。

我在收到“未授权”错误消息后:HttpResponseMessage response = await client.PostAsync(groupsEndpoint,createBody);

可能出现什么问题?

public static async Task<string> CreateGroupAsync(string groupName) {
        JObject jResult = null;
        string createdGroupId = null;
        try {
            HttpClient client = new HttpClient();
            var token = AuthenticationHelper.GetTokenForApplication();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            //I have removed the tenantID
            Uri groupsEndpoint = new Uri(Constants.GraphResourceUrl + "THIS_IS_WHERE_MY TENANT_ID_WOULD_BE/groups");


            string postBody = "{'mailEnabled':true," 
                            + "'displayName':'Group " + groupName + "',"
                            + "'mailNickName':'" + groupName + "',"
                            + "'securityEnabled':false," 
                            + "'groupTypes':unified" 
                            + "}";

            var createBody = new StringContent(postBody, System.Text.Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(groupsEndpoint, createBody);

            if (response.IsSuccessStatusCode) {
                string responseContent = await response.Content.ReadAsStringAsync();
                jResult = JObject.Parse(responseContent);
                createdGroupId = (string)jResult["id"];
                MessageBox.Show("Created group: " + createdGroupId);
            }
            else {
                MessageBox.Show("We could not create a group. The request returned this status code: " + response.StatusCode);
                return null;
            }
        }
        catch (Exception e) {
            MessageBox.Show("We could not create a group: " + e.Message);
            return null;
        }
        return createdGroupId;
    }

0 个答案:

没有答案