使用Rest API开发SharePoint Online

一、首先需要在扩展中引用3个dll:


System.Net.Http;
Microsoft.SharePoint.Client;
Microsoft.SharePoint.Client.Runtime;
在Nuget中安装Newtonsoft.dll

二、再新建两个类:



SPHttpClient.cs

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Call_SharePoint_Restful
{
    /// 
    /// Http client for SharePoint Online
    /// 
    public class SPHttpClient : HttpClient
    {

        public SPHttpClient(Uri webUri, string userName, string password)
            : base(new SPHttpClientHandler(webUri, userName, password))
        {
            BaseAddress = webUri;
        }


        /// 
        /// Execure request method
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public JObject ExecuteJson(string requestUri, HttpMethod method, IDictionary headers, T payload)
        {
            HttpResponseMessage response;
            switch (method.Method)
            {
                case "POST":
                    var requestContent = new StringContent(JsonConvert.SerializeObject(payload));
                    requestContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
                    DefaultRequestHeaders.Add("X-RequestDigest", RequestFormDigest());
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }
                    response = PostAsync(requestUri, requestContent).Result;
                    break;
                case "GET":
                    response = GetAsync(requestUri).Result;
                    break;
                default:
                    throw new NotSupportedException(string.Format("Method {0} is not supported", method.Method));
            }

            response.EnsureSuccessStatusCode();
            var responseContent = response.Content.ReadAsStringAsync().Result;
            return String.IsNullOrEmpty(responseContent) ? new JObject() : JObject.Parse(responseContent);
        }

        public JObject ExecuteJson(string requestUri, HttpMethod method, T payload)
        {
            return ExecuteJson(requestUri, method, null, payload);
        }

        public JObject ExecuteJson(string requestUri)
        {
            return ExecuteJson(requestUri, HttpMethod.Get, null, default(string));
        }


        /// 
        /// Request Form Digest
        /// 
        /// 
        public string RequestFormDigest()
        {
            var endpointUrl = string.Format("{0}/_api/contextinfo", BaseAddress);
            var result = this.PostAsync(endpointUrl, new StringContent(string.Empty)).Result;
            result.EnsureSuccessStatusCode();
            var content = result.Content.ReadAsStringAsync().Result;
            var contentJson = JObject.Parse(content);
            return contentJson["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }
    }
}



SPHttpClientHandler.cs


using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace Call_SharePoint_Restful
{
    public class SPHttpClientHandler : HttpClientHandler
    {
        public SPHttpClientHandler(Uri webUri, string userName, string password)
        {
            CookieContainer = GetAuthCookies(webUri, userName, password);
            FormatType = FormatType.JsonVerbose;
        }


        protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            if (FormatType == FormatType.JsonVerbose)
            {
                //request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json;odata=verbose"));
                request.Headers.Add("Accept", "application/json;odata=verbose");
            }
            return base.SendAsync(request, cancellationToken);
        }


        /// 
        /// Retrieve SPO Auth Cookies 
        /// 
        /// 
        /// 
        /// 
        /// 
        private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
        {
            var securePassword = new SecureString();
            foreach (var c in password) { 
                securePassword.AppendChar(c); 
            }
            var credentials = new SharePointOnlineCredentials(userName, securePassword);
            var authCookie = credentials.GetAuthenticationCookie(webUri);
            var cookieContainer = new CookieContainer();
            cookieContainer.SetCookies(webUri, authCookie);
            return cookieContainer;
        }


        public FormatType FormatType { get; set; }
    }

    public enum FormatType
    {
        JsonVerbose,
        Xml
    }
}


三、以下是调用的代码:



如何获取所有列表项

using (var client = new SPHttpClient(webUri, userName, password))
{
    var listTitle = "Tasks";
    var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items",webUri,listTitle);
    var data = client.ExecuteJson(endpointUrl);
    foreach (var item in data["value"])
    {
        Console.WriteLine(item["Title"]);
    }
}


如何获取指定的列表项

using (var client = new SPHttpClient(webUri, userName, password))
{
    var listTitle = "Tasks";
    var itemId = 1;
    var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items({2})",webUri,listTitle,itemId);
    var data = client.ExecuteJson(endpointUrl);
    Console.WriteLine(data["Title"]);
}


如何创建列表项

using (var client = new SPHttpClient(webUri, userName, password))
{
    var listTitle = "Tasks";
    var itemPayload = new {  __metadata = new { type = "SP.Data.TasksListItem" }, Title =  "Approval Task"};
    var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items",webUri,listTitle);
    var data = client.ExecuteJson(endpointUrl,HttpMethod.Post,itemPayload);
    Console.WriteLine("Task item '{0}' has been created",data["Title"]);
}


如何更新列表项

using (var client = new SPHttpClient(webUri, userName, password))
{
    var listTitle = "Tasks";
    var itemId = 1;
    var itemPayload = new {  __metadata = new { type = "SP.Data.TasksListItem" }, Title =  "Approval Task"};
    var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items({2})",webUri,listTitle,itemId);
    var headers = new Dictionary();
    headers["IF-MATCH"] = "*";
    headers["X-HTTP-Method"] = "MERGE";
    client.ExecuteJson(endpointUrl,HttpMethod.Post,headers, itemPayload);
    Console.WriteLine("Task item has been updated");
}


如何删除列表项

using (var client = new SPHttpClient(webUri, userName, password))
{
    var listTitle = "Tasks";
    var itemId = 2;
    var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items({2})",webUri,listTitle,itemId);
    var headers = new Dictionary();
    headers["IF-MATCH"] = "*";
    headers["X-HTTP-Method"] = "DELETE";
    client.ExecuteJson(endpointUrl,HttpMethod.Post,null,headers);
    Console.WriteLine("Task item has been deleted");
}



原文:https://blog.vgrem.com/2015/04/04/consume-sharepoint-online-rest-service-using-net/
























你可能感兴趣的:(SharePoint,开发教程,Restful)