C#代码使用Rest API调用更新SharePoint列表项

时间:2019-01-18 11:20:42

标签: c# sharepoint

我必须通过Rest Api调用来更新共享点中的列表项,

要求:

SharePoint类型:在线

更新代码:C#Rest API调用

异常:System.dll中发生了类型为'System.Net.WebException'的未处理异常

其他信息:远程服务器返回错误:(403)禁止。

public class Class1
{
    public static void Main()
    {

        string result = string.Empty;
        Uri uri = new Uri("http://serviceportal.xxx.com/_api/lists/getbytitle('List name')/items(1)");
        HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
        wreq.Credentials = CredentialCache.DefaultNetworkCredentials;

        wreq.Method = "POST";
        wreq.Accept = "application/json; odata=verbose";
        wreq.ContentType = "application/json; odata=verbose";
        wreq.Headers.Add("X-HTTP-Method", "MERGE");
        wreq.Headers.Add("IF-MATCH", "*");
        wreq.Headers.Add("X-RequestDigest", null);

        string stringData = "{'__metadata': { 'type': 'SP.Data.TestlistListItem' }, 'Title': 'whatever'}";
        wreq.ContentLength = stringData.Length;
        StreamWriter writer = new StreamWriter(wreq.GetRequestStream());
        writer.Write(stringData);
        writer.Flush();

        WebResponse wresp = wreq.GetResponse();
        using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
        {
            result = sr.ReadToEnd();
        }


    }
}

}

如何克服以上例外情况,是否有任何代码可用于使用Rest API调用的SharePoint中的SharePoint更新列表项。

1 个答案:

答案 0 :(得分:0)

您应该传递有效的SharePoint Online用户名和密码以获取表单摘要值,并在请求标头中使用此摘要值,而不是在代码段中使用null。 这是一个代码示例供您参考:

SPHttpClient.cs和SPHttpClientHandler.cs:

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

    namespace SPORestConsole
    {
        public class SPHttpClient: HttpClient
        {
            public SPHttpClient(Uri webUri, string userName, string password) : base(new SPHttpClientHandler(webUri, userName, password))
            {
                BaseAddress = webUri;
            }
            /// <summary>
            /// Execure request method
            /// </summary>
            /// <param name="requestUri"></param>
            /// <param name="method"></param>
            /// <param name="headers"></param>
            /// <param name="payload"></param>
            /// <returns></returns>
            public JObject ExecuteJson<T>(string requestUri, HttpMethod method, IDictionary<string, string> 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<T>(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));
            }


            /// <summary>
            /// Request Form Digest
            /// </summary>
            /// <returns></returns>
            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();
            }
        }
    }


    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 SPORestConsole
    {
        public class SPHttpClientHandler : HttpClientHandler
        {
            public SPHttpClientHandler(Uri webUri, string userName, string password)
            {
                CookieContainer = GetAuthCookies(webUri, userName, password);
                FormatType = FormatType.JsonVerbose;
            }


            protected override Task<HttpResponseMessage> 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);
            }


            /// <summary>
            /// Retrieve SPO Auth Cookies 
            /// </summary>
            /// <param name="webUri"></param>
            /// <param name="userName"></param>
            /// <param name="password"></param>
            /// <returns></returns>
            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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SPORestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri uri = new Uri ("https://tenantname.sharepoint.com/sites/dev/");
            using (var client = new SPHttpClient(uri, "username@tanantname.onmicrosoft.com", "yourpassword"))
            {
                var listTitle = "MyList8";
                var itemId = 4;
                var itemPayload = new { __metadata = new { type = "SP.Data.MyList8ListItem" }, Title = "updateviaRest" };
                var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items({2})", uri, listTitle, itemId);
                var headers = new Dictionary<string, string>();
                headers["IF-MATCH"] = "*";
                headers["X-HTTP-Method"] = "MERGE";
                client.ExecuteJson(endpointUrl, HttpMethod.Post, headers, itemPayload);
                Console.WriteLine("Task item has been updated");
            }
        }
    }
}

enter image description here

参考:

Consume SharePoint Online REST service using .NET