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

时间:2014-08-25 01:02:46

标签: c# json rest post office365

我正在尝试使用Office API来同步来自几个不同来源的联系人。尝试使用我的JSON对象发出POST请求以创建新联系人时遇到问题。我一直在查看MSDN页面,但我觉得我应该澄清一下我对C#相对较新,这是我第一次尝试在C#中使用REST协议和异步方法。

我的代码如下,我尝试创建一个类,它将添加一个带有硬编码JSON字符串的新联系人。我尝试了几种尝试完成此请求的方法。我尝试过的每个请求都会给我一个401或400错误。我留下了一些我认为最接近解决方案的线路,但如果这些线路不在正确的轨道上,那么尝试别的东西也没问题。我认为还有一个功能可能很有用但我无法找到有关如何使用它的文档:

await client.Me.Contacts.AddContactAsync();

我再次说我对此很新,所以如果有办法从JSON创建IContact项并使用上面的方法或直接传递JSON要么非常有用。甚至链接到我希望看到的可能有用的文档。我对这个问题很不满意我以前从来没有发过一个问题,但我对此感到难过。

以下是Contacts API的文档,也许对你们来说比我更有意义。

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

如果有人能够弄清楚如何从该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);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

嗯,我想我想出了一个解决方法。这使用我创建的ContactObject和newtonsoft的JSON序列化程序。我希望看到一个微软ExchangeClient实例的例子,我发布这个的唯一原因是为了帮助其他可能有类似问题的人发布到办公室API,下面的代码将成功运行。我还在寻找是否有人能告诉我使用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");
        }
    }