Search code examples
c#.netrestoffice365

Office 365 REST API - Creating a Contact gives me HTTPCode 400


I am using the Office 365 Rest API and I am having problems in creating a Contact:

I am doing this:

public async Task<bool> CreateContact(Contact contact)
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://outlook.office365.com/ews/odata/Me/Contacts"));

        // Add the Authorization header with the basic login credentials.
        var auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(_user + ":" + _password));
        request.Headers.Add("Accept", "application/json");
        request.Headers.Add("Authorization", auth);
        var createResponse = new JObject();
        createResponse["@odata.type"] = "#Microsoft.Exchange.Services.OData.Model.Contact";
        createResponse["DisplayName"] = contact.Name;
        createResponse["EmailAddress1"] = contact.Email;
        request.Content = new StringContent(JsonConvert.SerializeObject(createResponse), Encoding.UTF8, "application/json;odata.metadata=full");
        
        var response = await client.SendAsync(request);
        if (response.IsSuccessStatusCode)
        {
            return true;
        }
        return false;
    }

that give me

{System.FormatException: The format of value 'application/json;odata.metadata=full' is invalid.
    at System.Net.Http.Headers.MediaTypeHeaderValue.CheckMediaTypeFormat(String mediaType, String parameterName)
   at System.Net.Http.Headers.MediaTypeHeaderValue..ctor(String mediaType)
   at System.Net.Http.StringContent..ctor(String content, Encoding encoding, String mediaType)
   at SharePointPTSample.Office365.Office365Service.<CreateContact>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at SharePointPTSample.ViewModels.EditContactViewModel.<SaveContact>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__3(Object state)}

but if I change the value "application/json;odata.metadata=full" to "application/json", It gives me 400

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 0.0, Content: System.Net.Http.StreamContent, Headers:
{
  Cache-Control: private
  Server: Microsoft-IIS/8.0
  request-id: 3679d732-ae03-4358-b256-3738cbf24030
  X-CalculatedBETarget: dbxpr06mb352.eurprd06.prod.outlook.com
  X-DiagInfo: DBXPR06MB352
  X-BEServer: DBXPR06MB352
  X-AspNet-Version: 4.0.30319
  Set-Cookie: exchangecookie=daa5b4f2b05b422f8c5e99105e617429; expires=Sun, 05-Jul-2015 22:06:47 GMT; path=/; HttpOnly,  X-BackEndCookie=< removed it for post>; expires=Mon, 04-Aug-2014 22:06:47 GMT; path=/ews; secure; HttpOnly
  X-Powered-By: ASP.NET
  X-FEServer: AMXPR05CA0040
  Date: Sat, 05 Jul 2014 22:06:47 GMT
  Content-Length: 567
  Content-Type: application/json; odata.metadata=minimal; odata.streaming=true; IEEE754Compatible=false; charset=utf-8
}}

I follow this link

http://msdn.microsoft.com/en-us/library/office/dn605896(v=office.15).aspx#bkContact

What is missing? I did not undertand :/

I have Delete, Update and GetContacts working.

The complete source code is here: https://github.com/saramgsilva/Office365RESTAPISample


Solution

  • saramgsilva, Thanks for trying the API. I tried your code and a couple of things. 1. You need to specify ContentType Header as application/json. Leave the odata part out. 2. After you give that, you would have seen the next issue, which is that Given name is required. Once you provide these two, you should get a 201.

            createResponse["GivenName"] = "Rohit1";
            request.Content = new StringContent(JsonConvert.SerializeObject(createResponse));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");