如何使用C#中的SharePoint Online 2013 Rest API删除列表项

时间:2015-07-02 03:32:39

标签: c# rest sharepoint-2013

我正在尝试使用带有C#托管代码的REST API从SharePoint 2013 Online中删除列表项。

这是我的代码的本质:

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);
}

我获得了403权限被拒绝,但使用类似模式我可以创建一个列表项。我使用的是WebClient的凭据,这是一个SharePointOnlineCredentials对象。我是SharePoint站点管理员。

所以,我想知道我的语法/方法是否错误。假设我没有权限问题,有人可以验证我的代码“应该”工作吗?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案:

客户端标头需要包含表单摘要:

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

要获取表单摘要,您可以使用以下代码:

    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();
    }

注意:凭据也很棘手,这是代码:

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

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