【问题标题】:Office 365 REST API - Adding a Contact with JSON in C#Office 365 REST API - 在 C# 中使用 JSON 添加联系人
【发布时间】:2014-08-25 01:02:46
【问题描述】:

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

【问题讨论】:

    标签: c# json rest post office365


    【解决方案1】:

    好吧,我想我想出了一个解决办法。这使用了我创建的 ContactObject 和 newtonsoft 的 JSON 序列化程序。我希望看到一个 Microsoft ExchangeClient 的示例,我发布此内容的唯一原因是帮助其他可能有类似问题的人发布到 Office 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");
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多