Microsoft Graph Post操作创建组“错误请求”

时间:2018-08-30 09:12:38

标签: c# microsoft-graph

我们正尝试向Microsoft Graph API发出请求以创建组,如解释的HERE

基本网址为: https://graph.microsoft.com/v1.0/groups 内容类型设置为apllication / json 我们也有一个有效的Baerer令牌。

我们正在使用Microsoft.Graph命名空间(NuGet包)中的Group类,因此我们用数据填充属性,并调用JsonConvert.SerializeObject(group)将组对象序列化为Json。

这是我们构建和序列化的方式:

 Microsoft.Graph.Group group = new Microsoft.Graph.Group();
                group.Description = "Self help community for library";
                group.DisplayName = "Library Assist";
                group.GroupTypes = new[] { "Unified" };
                group.MailEnabled = true;
                group.MailNickname = "library";
                group.SecurityEnabled = true;

   string json = JsonConvert.SerializeObject(group);

   var content = new StringContent(json);
   var response = httpclient.PostAsJsonAsync(Uri, content).Result;

HttpClient的标头设置如下:

 httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "...value of baerer token...");
 httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

我们正在从https://graph.microsoft.com/v1.0开始构建URL 向其中添加/groups

在响应中,我们得到一个Bad request status code 400。 这表示请求URI,标头或正文中有错误,但是在Graph Explorer中,与上面相同的代码可以正常工作,我们在响应中得到结果。 我要监督什么?

感谢您的任何反馈或建议。 此致。

1 个答案:

答案 0 :(得分:3)

由于您已经在使用Microsoft.Graph命名空间,因此可以使用内置的GraphServiceClient发出请求,如下所示。您无需使用http客户端或序列化对象,这将得到处理:

var graphserviceClient = new GraphServiceClient(
    new DelegateAuthenticationProvider(
        (requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", "<your-access-token>");              
        }));

var group = new Microsoft.Graph.Group
{
    DisplayName = "Library Assist",
    Description = "Self help community for library",
    MailNickname = "library",
    MailEnabled = true,
    SecurityEnabled = true,
    GroupTypes = new List<string> { "Unified" }
};      

var createdGroup = await graphserviceClient.Groups.Request().AddAsync(group);

参考-Intro to the Microsoft Graph .NET Client Library