Insert item into list via REST

I am creating a WCF service in which I perform CRUD operations in a sharepoint list. I got the data from the sharepoint list successfully through REST, that is, I transferred the credentials (username, password, domain) through the network credential object, but, unfortunately, I could not insert the data. The error relates to unauthorized access while inserting data into sharepoint. Then I tried the Sharepoint credential object online, but no luck. I need help.

Here is the exception:

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

Here is the code:

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)
{
}
+4
source share
1 answer

, Create, Update Delete Request Digest SharePoint Online/Office 365.

Request Digest

X-RequestDigest , , , .

WebClient SharePoint 2013/SharePoint Online

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 Info, .

-

: [ Json.NET] [1]

, Contacts List:

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

All Articles