通过REST在列表中插入项目

use*_*253 4 c# rest sharepoint wcf webclient

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

这是一个例外:

The remote server returned an error: (401) Unauthorized.
Run Code Online (Sandbox Code Playgroud)

这是代码:

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)
{
}
Run Code Online (Sandbox Code Playgroud)

Vad*_*hev 5

发生此错误,因为Request Digest必须在SharePoint Online/Office 365中的请求期间指定执行创建,更新或删除操作值.

关于 Request Digest

X-RequestDigest header存储一个安全验证令牌,该令牌允许帮助防止用户被欺骗将数据发布到服务器而不知道它的攻击类型.

如何在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;

    }
}
Run Code Online (Sandbox Code Playgroud)

要点:[ListsClient.cs] [2]

注意:由于SharePoint要求用户在每次创建,更新和删除操作RequestFormDigest method中包含请求摘要值,因此使用请求包含请求摘要值的上下文信息实体来调用其他请求.

-

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

用法

以下示例演示如何在ContactsList中创建List Item :

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