我正在尝试在 Office 365 中创建联系人。“PostJson()”方法引发以下错误。
远程服务器返回错误:(400) 错误请求。
我已经在 Azure AD 中注册了应用程序并获得了所需的权限。我跟着这篇文章。
我正在使用 WebAPI .Net Core。以下是我的代码。任何帮助表示赞赏。
public async Task<string> AcquireToken()
{
var tenant = "red.onmicrosoft.com";
var resource = "https://graph.microsoft.com/";
var instance = "https://login.microsoftonline.com/";
var clientID = "db19fbcc-d1e8-4d60-xxxx-xxxxxxxxxx";
var secret = "EXh3MNe5tGW8+Jh1/3OXXXRvEKqdxuuXXXXXXX=";
var authority = $"{instance}{tenant}";
var authContext = new AuthenticationContext(authority);
var credentials = new ClientCredential(clientID, secret);
var authResult = await authContext.AcquireTokenAsync(resource, credentials);
return authResult.AccessToken;
}
public static string PostJson(string token)
{
Contact contact = new Contact()
{
givenName = "Pavel",
surname = "Bansky"
};
contact.emailAddresses.Add(new emailAddresses()
{
address = "pavelb@doneitsoftware.com",
name = "Pavel Bansky"
});
contact.businessPhones.Add("+1 732 555 0102");
var jsonString = JsonConvert.SerializeObject(contact);
string body = jsonString.ToString();
HttpWebRequest hwr = (HttpWebRequest) WebRequest
.CreateHttp("https://graph.microsoft.com/v1.0/me/contacts");
hwr.Method = "POST";
hwr.Headers.Add("Authorization", "Bearer " + token);
hwr.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
hwr.ContentType = "application/json";
var postData = Encoding.UTF8.GetBytes(body.ToString());
using(var stream = hwr.GetRequestStream())
{
stream.Write(postData, 0, postData.Length);
}
三国纷争
相关分类