Reputation: 12711
I'm trying to create a contact in office 365. "PostJson()" method throws the following error.
The remote server returned an error: (400) Bad Request.
I have registered the application in Azure AD and given the required permissions. I followed this article.
I'm using WebAPI .Net Core. Following is my code. Any help is appreciated.
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 = "[email protected]",
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" };
}
Upvotes: 1
Views: 287
Reputation: 27528
One problem in your codes is you are using the wrong API , since you are using the client credential flow to acquire access token using app's identity , you should use below api to create contact :
POST /users/{id | userPrincipalName}/contacts
I test your codes with objects:
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; }
}
And it works fine . Please try to modify the api call , if error still occur ,please provide the detailed/inner error message .
Upvotes: 1