Я пытаюсь выполнить операцию CRUD для Azure B2C через приложение MVC. Следующее приложение работает для получения пользовательских данных, то есть GET
. Но метод POST
для создания нового пользователя не работает. POST
Способ дает ответ с Status Code
400, Причина Phrase:Bad Request
. Я добавил эти два метода для достижения функциональности CR в проекте в GitHub: Microsoft Graph SDK ASPNET ConnectОШИБКА: Azure B2C Создайте пользователя методом post из веб-приложения
public async Task<string> UpdateUserDetails(string accessToken)
{
string jsondata = File.ReadAllText("C:\\usertemplate-email.json");
string endpoint = "https://graph.microsoft.com/v1.0/users";
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Content = new StringContent(JsonConvert.SerializeObject(jsondata), Encoding.UTF8, "application/json");
//didn't received successStatusCode with or without searilizing jasondata
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
//Status Code: 400, Reason Phrase:Bad Request
var json = JObject.Parse(await response.Content.ReadAsStringAsync());
}
return response.ReasonPhrase;
}
}
}
}
public async Task<string> GetUserDetails(string accessToken)
{
// Get the current user.
// The app only needs the user's email address, so select the mail and userPrincipalName properties.
// If the mail property isn't defined, userPrincipalName should map to the email for all account types.
string endpoint = "https://graph.microsoft.com/v1.0/users/4b4442a8-bd02-4992-9c62-b1b31807428d";
using (var client = new HttpClient())
{
//if no queryParameter parameter is passed, all parameters will be selected
using (var request = new HttpRequestMessage(HttpMethod.Get, endpoint))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (response.StatusCode == HttpStatusCode.OK)
{
var json = JObject.Parse(await response.Content.ReadAsStringAsync());
//got the expected result at this point
}
return response.ReasonPhrase;
}
}
}
}
включаемый файл в формате JSON:
{
"accountEnabled": true,
"signInNames": [
{
"type": "emailAddress",
"value": "[email protected]"
}
],
"creationType": "LocalAccount",
"displayName": "Joe Consumer",
"mailNickname": "joec",
"passwordProfile": {
"password": "[email protected]!",
"forceChangePasswordNextLogin": false
},
"passwordPolicies": "DisablePasswordExpiration",
"city": "San Diego",
"country": null,
"facsimileTelephoneNumber": null,
"givenName": "Joe",
"mail": null,
"mobile": null,
"otherMails": [],
"postalCode": "92130",
"preferredLanguage": null,
"state": "California",
"streetAddress": null,
"surname": "Consumer",
"telephoneNumber": null
}
Спасибо @gfyans. Я думаю, что это связано не с API-интерфейсом Microsoft Graph, поскольку я могу заставить его работать для методов GET и PATCH. Это может быть вызвано вложенным объектом во входные данные json, где сериализация вызывает ошибку формата. –