Carl Stewart
Carl Stewart

Reputation: 335

How to delete list item using SharePoint Online 2013 Rest API in C#

I am trying to delete a list item from SharePoint 2013 Online using the REST APIs with C# managed code.

Here's the essence of my code:

using (var client = new WebClient())
{
    client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    client.Credentials = mySPCreds;

    client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
    client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");

    client.Headers.Add("X-HTTP-Method", "DELETE");
    client.Headers.Add("IF-MATCH", "*");

    var requestUri = new Uri("https://mysharepointsite.../_api/web/lists/getbytitle('MyList')/items(123)");

    client.UploadString(requestUri, String.Empty);
}

I'm getting a 403 permission denied, but using a similar pattern I am able to create a list item. I am using my credentials for the WebClient which is a SharePointOnlineCredentials object. I am a SharePoint site administrator.

So, I am wondering if I just have the syntax/approach wrong. Can someone verify that my code above "should" work assuming I don't have permissions issues?

Upvotes: 3

Views: 1930

Answers (1)

Carl Stewart
Carl Stewart

Reputation: 335

Ok, I found the solution:

The client headers need to include the form digest:

client.Headers.Add("X-RequestDigest", GetFormDigest());

To get the form digest, you can use this code:

    private string GetFormDigest()
    {
        var webClient = new WebClient();
        webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        webClient.Credentials = this.Credentials;
        webClient.Headers.Add(HttpRequestHeader.ContentType, String.Format("application/json;odata=nometadata"));
        webClient.Headers.Add(HttpRequestHeader.Accept, String.Format("application/json;odata=nometadata"));

        var uri = new Uri(this.SharepointBaseURL);
        var endpointUri = new Uri(uri, "_api/contextinfo");
        var result = webClient.UploadString(endpointUri, "POST");
        JToken t = JToken.Parse(result);

        //Use this if odata = nometadata
        return t["FormDigestValue"].ToString();

        //Use this if odata = verbose
        //return t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
    }

NOTE: Credentials are tricky too, here's the code for that:

        var securePassword = new SecureString();
        foreach (var c in myPassword)
        {
            securePassword.AppendChar(c);
        }

        this.Credentials = new SharePointOnlineCredentials(myUserName, securePassword);

Upvotes: 1

Related Questions