通过REST在列表中插入项目

本文关键字:插入项目 列表 REST 通过 | 更新日期: 2023-09-27 18:20:20

我正在创建一个WCF服务,在其中执行sharepoint列表中的CRUD操作。我已经通过REST成功地从sharepoint列表中检索到数据,即通过网络凭据对象传递凭据(用户名、密码、域),但不幸的是无法插入数据。该错误是指在sharepoint中插入数据时未经授权的访问。然后我尝试了Sharepoint在线凭据对象,但没有成功。我需要一些帮助。

这里有一个例外:

The remote server returned an error: (401) Unauthorized.

这是代码:

try
{
                        string userPassword = "password";
                        WebClient webClient = new WebClient();
                        SecureString securePassword = new SecureString();
                        for (int i = 0; i < userPassword.Length; i++)
                        {
                            securePassword.AppendChar(userPassword[i]);
                        }
                        webClient.Credentials = new SharePointOnlineCredentials(@"username@domain", securePassword);
                        webClient.Headers.Add("Content-type", "application/json");
                        webClient.Headers.Add("Accept", "application/json;odata=verbose");
                        webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
                        webClient.Encoding = Encoding.UTF8;
                        string msg = webClient.UploadString("http://abc:9211/sites/api/_api/web/lists/getbytitle('list_name')/Items", "POST", "{__metadata'":{'"type'":'"SP.Data.SubscriptionListItem'"},'"UserID'":'"user'",'"SubscriptionType'":'"Type1'",'"Title'":'"Testing'"}");
}
catch(WebException ex)
{
}

通过REST在列表中插入项目

由于要执行创建、更新或删除操作,必须在SharePoint Online/Office 365中的请求过程中指定Request Digest值,因此会发生此错误。

关于Request Digest

X-RequestDigest标头存储一个安全验证令牌,该令牌允许帮助防止用户在不知情的情况下被诱骗向服务器发布数据的攻击类型

如何在SharePoint 2013/SharePoint Online中通过WebClient创建列表项

using System;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SPORestClient
{
    /// <summary>
    /// Client for performing CRUD operations against List resource in SharePoint Online (SPO) 
    /// </summary>
    public class ListsClient : IDisposable
    {
        public ListsClient(Uri webUri, ICredentials credentials)
        {
            _client = new WebClient();
            _client.Credentials = credentials;
            _client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            _client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
            _client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
            WebUri = webUri;
        }
        public void InsertListItem(string listTitle, object payload)
        {
            var formDigestValue = RequestFormDigest();
            _client.Headers.Add("X-RequestDigest", formDigestValue);
            var endpointUri = new Uri(WebUri, string.Format("/_api/web/lists/getbytitle('{0}')/items", listTitle));
            var payloadString = JsonConvert.SerializeObject(payload);
            _client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
            _client.UploadString(endpointUri, "POST", payloadString);
        }
        /// <summary>
        /// Request Form Digest
        /// </summary>
        /// <returns></returns>
        private string RequestFormDigest()
        {
            var endpointUri = new Uri(WebUri, "_api/contextinfo");
            var result = _client.UploadString(endpointUri, "POST");
            JToken t = JToken.Parse(result);
            return t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }

        public Uri WebUri { get; private set; }
        public void Dispose()
        {
            _client.Dispose();
            GC.SuppressFinalize(this);
        }
        private readonly WebClient _client;
    }
}

Gist:[ListsClient.cs][2]

注意:由于SharePoint要求用户包含请求摘要每个创建、更新和删除操作的值使用RequestFormDigest method调用请求以请求上下文包含请求摘要值的信息实体。

--

依赖项:[Json.NET库][1]

使用

以下示例演示如何在Contacts列表中创建列表项:

using (var client = new ListsClient(webUri, credentials))
{
    var contactEntry = new
    {
        __metadata = new { type = "SP.Data.ContactsListItem" },
        Title = "John Doe"
    };
    client.InsertListItem("Contacts", contactEntry);
}