我正在尝试在 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); }
1 回答
三国纷争
TA贡献1804条经验 获得超7个赞
您的代码中的一个问题是您使用了错误的 API,因为您使用客户端凭据流来获取使用应用程序身份的访问令牌,您应该使用以下 api 来创建联系人:
POST /users/{id | userPrincipalName}/contacts
我用对象测试你的代码:
public class Contact {
public string givenName { get; set; }
public string surname { get; set; }
public List<emailAddresses> emailAddresses { get; set; }
public List<string> businessPhones { get; set; }
}
public class emailAddresses {
public string address { get; set; }
public string name { get; set; }
}
它工作正常。请尝试修改api调用,如果仍然出现错误,请提供详细/内部错误消息。
- 1 回答
- 0 关注
- 61 浏览
添加回答
举报
0/150
提交
取消