创建联系人返回 HTTP 400 - 错误请求

我正在尝试在 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);

    }


紫衣仙女
浏览 62回答 1
1回答

三国纷争

您的代码中的一个问题是您使用了错误的 API,因为您使用客户端凭据流来获取使用应用程序身份的访问令牌,您应该使用以下 api 来创建联系人:POST /users/{id | userPrincipalName}/contacts我用对象测试你的代码:&nbsp;public class Contact {&nbsp; &nbsp; &nbsp; &nbsp; public string givenName { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public string surname { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public List<emailAddresses> emailAddresses { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public List<string> businessPhones { get; set; }&nbsp; &nbsp; }&nbsp; &nbsp; public class emailAddresses {&nbsp; &nbsp; &nbsp; &nbsp; public string address { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public string name { get; set; }&nbsp; &nbsp; }它工作正常。请尝试修改api调用,如果仍然出现错误,请提供详细/内部错误消息。
打开App,查看更多内容
随时随地看视频慕课网APP