我正在尝试在Office 365中创建联系人。“ PostJson()”方法引发以下错误。
远程服务器返回错误:(400)错误的请求。
我已经在Azure AD中注册了该应用程序并获得了所需的权限。我关注了this article。
我正在使用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);
}
WebResponse response = null;
try
{
response = hwr.GetResponse();
using(Stream stream = response.GetResponseStream())
{
using(StreamReader sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
}
catch (Exception e)
{
throw e;
}
}
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> GetAsync()
{
Office365Manager office = new Office365Manager();
string aa = await office.AcquireToken();
Office365Manager.PostJson(aa.ToString());
return new string[] { "value1", "value2" };
}
答案 0 :(得分:1)
代码中的一个问题是您使用了错误的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调用,如果仍然发生错误,请提供详细/内部错误消息。