我对Microsoft Graph API有疑问。 我尝试在C#程序中通过REST API调用创建一个组,并且我一直收到“未授权”错误。
我在收到“未授权”错误消息后: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;
}