我正在尝试在 Microsoft 文档的帮助下使用 Microsoft Graph (v1.0) 在我的租户中创建一个新用户。
当我创建我的用户时,我总是收到一个 error 400 bad request
作为响应。
我正在使用 HttpClient 发出帖子请求。
我的功能:
private async Task<string> BuildUser(string token, string query)
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
UserCreation uc = new UserCreation
{
accountEnabled = this.checkBoxActive.Checked,
displayName = this.textBoxDN.Text,
mailNickName = this.textBoxMail.Text,
passwordProfile = new PasswordProfile { forceChangePasswordNextSignIn = this.checkBoxChangeMDP.Checked, password = this.textBoxPassword.Text},
userPrincipalName = this.textBoxUPN.Text
};
string json = JsonConvert.SerializeObject(uc);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync(query, content).Result;
return response.ToString();
}
我的 token 有效,我可以发出简单的 Get 请求,我的应用程序具有提到的授权 here .
例如,我的 json var 可以包含:
{
"accountEnabled":true,
"displayName":"cyril testgraphh",
"mailNickName":"cyriltestgraphh",
"userPrincipalName":"cyriltestgraphh@mytenant.fr",
"passwordProfile":{
"forceChangePasswordNextSignIn":true,
"password":"XXX"
}
}
编辑: 我通过使用 Microsoft Graph 对象(Microsoft.Graph.User 和 Microsoft.Graph.PasswordProfile)解决了我的问题,并将 .onmicrosoft.com 添加到我的 upn
最佳答案
你应该检查你的代码。我尝试了以下代码,效果很好。
using Microsoft.Graph;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
UserCreation uc = new UserCreation
{
accountEnabled = true,
displayName = "cyril testgraphh",
mailNickName = "cyriltestgraphh",
passwordProfile = new PasswordProfile { ForceChangePasswordNextSignIn = false, Password = "Password!" },
userPrincipalName = "XXXXXX@jmaster.onmicrosoft.com"
};
string json = JsonConvert.SerializeObject(uc);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync("https://graph.microsoft.com/v1.0/users", content).Result;
Console.Write(response);
Console.ReadLine();
}
}
class UserCreation
{
public bool accountEnabled { get; internal set; }
public string displayName { get; internal set; }
public string mailNickName { get; internal set; }
public string userPrincipalName { get; internal set; }
public PasswordProfile passwordProfile { get; internal set; }
}
}
响应如下:
关于c# - 错误 400 - 使用 Microsoft Graph 错误请求创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648111/