简体   繁体   English

Office 365 REST API-在C#中使用JSON添加联系人

[英]Office 365 REST API - Adding a Contact with JSON in C#

I am trying to use the Office API to sync contacts from a few different sources. 我正在尝试使用Office API来同步来自几个不同来源的联系人。 I have been having a problem trying to make a POST request with my JSON object to create a new contact. 我尝试用JSON对象发出POST请求以创建新联系人时遇到问题。 I have been looking at the MSDN pages but I feel like I should clarify I'm relatively new to C#, this is my first time trying to use REST protocols, and async methods in C#. 我一直在看MSDN页面,但是我觉得我应该澄清一下我对C#还是比较陌生,这是我第一次尝试在C#中使用REST协议和异步方法。

I have my code below, I tried to create a class that will add a new contact with a hard coded JSON string. 我在下面有我的代码,我试图创建一个类,该类将添加带有硬编码JSON字符串的新联系人。 I have tried a few various ways of trying to complete this request. 我尝试了几种尝试完成此请求的方法。 Every request I have attempted gives me a 401 or 400 Error. 我尝试的每个请求都会给我401或400错误。 I left a couple lines that I felt were closest to the solution but if those are not on the right track I have no problem trying something else. 我留下了几条我觉得最接近解决方案的线,但是如果这些线不在正确的轨道上,那么尝试其他方法就没有问题。 There is also a function that I believe could be useful but I couldn't really find documentation on how to use it: 我相信还有一个功能可能有用,但是我找不到真正如何使用它的文档:

await client.Me.Contacts.AddContactAsync();

Again I said I am pretty new to this so if there is a way to create an IContact item from the JSON and use the above method or to just pass the JSON directly either would be extremely useful. 再次,我说我对此很陌生,因此,如果有一种方法可以从JSON创建IContact项并使用上述方法,或者仅直接传递JSON,则将非常有用。 Even links to documentation that could be useful I would love to see. 我什至希望看到甚至有用的文档链接。 I'm a pretty stuck on this problem I've never posted a question before but I'm stumped on this. 我对这个问题非常执着,以前从未发布过问题,但是对此我感到很困惑。

Below is the documentation for the Contacts API maybe it will make more sense to you guys than me. 以下是Contacts API的文档,也许对你们来说比我更有意义。

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

If anybody can figure out how to make a post request from that JSON it will be much appreciated. 如果有人能弄清楚如何从该JSON发出发布请求,将不胜感激。

using Microsoft.Office365.Exchange;
using Microsoft.Office365.OAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ContactSynchronization
{
    class OfficeAPIWrite
    {
        private static string odata = "@odata.type";
        private static string type = "#Microsoft.Exchange.Services.OData.Model.Contact";


        const string ServiceResourceId = "https://outlook.office365.com";
        static readonly Uri ServiceEndpointUri = new Uri("https://outlook.office365.com/ews/odata/Me/Contacts");

        static string _lastLoggedInUser;
        static DiscoveryContext _discoveryContext;

        public static async Task OfficeWrite()
        {
            try
            {
                var client = await EnsureClientCreated();

                string json = new JavaScriptSerializer().Serialize(new
                {
                    odata = type,
                    GivenName = "Mara",
                    Surname = "Whitley",
                    EmailAddress1 = "mara@fabrikam.com",
                    BusinessPhone1 = "425-555-1313",
                    Birthday = "1974-07-22T07:00:00Z"
                });

                try
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceEndpointUri);
                    request.Content = new StringContent(json);
                    request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }
                catch (System.Net.WebException e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            catch (Microsoft.Office365.OAuth.AuthenticationFailedException)
            {
                MessageBox.Show("Authentication Failed Exception was thrown");
            }
        }

        public static async Task<ExchangeClient> EnsureClientCreated()
        {
            if (_discoveryContext == null)
            {
                _discoveryContext = await DiscoveryContext.CreateAsync();
            }

            var dcr = await _discoveryContext.DiscoverResourceAsync(ServiceResourceId);

            _lastLoggedInUser = dcr.UserId;

            return new ExchangeClient(ServiceEndpointUri, async () =>
            {
                return (await _discoveryContext.AuthenticationContext.AcquireTokenSilentAsync(ServiceResourceId, _discoveryContext.AppIdentity.ClientId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(dcr.UserId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId))).AccessToken;
            });
        }

        public static async Task SignOut()
        {
            if (string.IsNullOrEmpty(_lastLoggedInUser))
            {
                return;
            }

            if (_discoveryContext == null)
            {
                _discoveryContext = await DiscoveryContext.CreateAsync();
            }

            await _discoveryContext.LogoutAsync(_lastLoggedInUser);
        }
    }
}

Well I guess I figured out a work around. 好吧,我想我已经找到解决方法。 This uses a ContactObject that I created and newtonsoft's JSON serializer. 这使用了我创建的ContactObject和newtonsoft的JSON序列化程序。 I was hoping to see an example of the microsoft ExchangeClient in action, the only reason I am posting this is to help others that might have similar issues posting to the office API, the below code will run successfully. 我希望看到一个运行中的Microsoft ExchangeClient的示例,我发布此消息的唯一原因是为了帮助其他可能将类似问题发布到Office API的人,以下代码将成功运行。 I'm still looking though if anybody can show me the correct way to use the ExchangeClient functions. 我仍然在寻找是否有人可以向我展示使用ExchangeClient函数的正确方法。

    // your request must include these, and a given name,
    // everything else is optional
    private const string odata = "@odata.type";
    private const string type = "#Microsoft.Exchange.Services.OData.Model.Contact";

    public static async Task CreateContact(ContactObject officeContact, string userEmail, string userPassword)
    {
        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(userEmail + ":" + userPassword));
        request.Headers.Add("Accept", "application/json");
        request.Headers.Add("Authorization", auth);

        var createResponse = new JObject();
        createResponse[odata] = type; // this needs to be here for this to work
        if (!String.IsNullOrEmpty(officeContact.officeDisplayName)) createResponse["DisplayName"] = officeContact.officeDisplayName;
        if (!String.IsNullOrEmpty(officeContact.officeGivenName)) createResponse["GivenName"] = officeContact.officeGivenName;
        if (!String.IsNullOrEmpty(officeContact.officeMiddleName)) createResponse["MiddleName"] = officeContact.officeMiddleName;
        if (!String.IsNullOrEmpty(officeContact.officeNickName)) createResponse["NickName"] = officeContact.officeNickName;
        if (!String.IsNullOrEmpty(officeContact.officeSurname)) createResponse["Surname"] = officeContact.officeSurname;
        if (!String.IsNullOrEmpty(officeContact.officeEmailAddress1)) createResponse["EmailAddress1"] = officeContact.officeEmailAddress1;
        if (!String.IsNullOrEmpty(officeContact.officeEmailAddress2)) createResponse["EmailAddress2"] = officeContact.officeEmailAddress2;
        if (!String.IsNullOrEmpty(officeContact.officeEmailAddress3)) createResponse["EmailAddress3"] = officeContact.officeEmailAddress3;
        if (!String.IsNullOrEmpty(officeContact.officeHomePhone1)) createResponse["HomePhone1"] = officeContact.officeHomePhone1;
        if (!String.IsNullOrEmpty(officeContact.officeHomePhone2)) createResponse["HomePhone2"] = officeContact.officeHomePhone2;
        if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone1)) createResponse["BusinessPhone1"] = officeContact.officeBusinessPhone1;
        if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone2)) createResponse["BusinessPhone2"] = officeContact.officeBusinessPhone2;
        if (!String.IsNullOrEmpty(officeContact.officeMobilePhone1)) createResponse["MobilePhone1"] = officeContact.officeMobilePhone1;
        if (!String.IsNullOrEmpty(officeContact.officeOtherPhone)) createResponse["OtherPhone"] = officeContact.officeOtherPhone;
        if (!String.IsNullOrEmpty(officeContact.officeId)) createResponse["Id"] = officeContact.officeId;
        if (!String.IsNullOrEmpty(officeContact.officeCompanyName)) createResponse["CompanyName"] = officeContact.officeCompanyName;

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

        var response = await client.SendAsync(request);

        try
        {
            response.EnsureSuccessStatusCode();
        }
        catch (System.Net.WebException)
        {
            MessageBox.Show("BAD REQUEST");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM