none
SharePoint REST and C# Sample to UPDATE LIST ITEM RRS feed

  • Question

  • Somehow I am not able to find a very basic sample of SharePoint REST.

    My requirements are

    1. C# (no javascript)

    2. REST (no CSOM)

    3. Update List Item (not just list title)

    I did search and find many many resources

    http://social.msdn.microsoft.com/Forums/en-US/b1d103a4-71c9-423c-8403-e3dbf519c089/updating-list-items-in-a-document-library-using-sharepoint-2013-rest-api-c?forum=sharepointdevelopment

    But they don't contain the answer because 

    1. they just change the list title and not the item.

    2. use java script

    3. Use some very generic tutorial about REST without the specifics of how to update a list item using REST and C#.

    I think this is what I am looking for

    url: http://site url/_api/web/lists/GetByTitle(‘Test')/items(item id)
    method: POST
    body: { '__metadata': { 'type': 'SP.Data.TestListItem' }, 'Title': 'TestUpdated'}
    headers:
        Authorization: "Bearer " + accessToken
         X-RequestDigest: form digest value
        “IF-MATCH”: etag or “*”
        “X-HTTP-Method”:”MERGE”,
        accept: "application/json;odata=verbose"
        content-type: "application/json;odata=verbose"
        content-length:length of post body

    But I don't know how to convert this into a C# Console Application. (No JavaScript, No Auto-hosted).


    • Edited by MSDN Student Thursday, February 13, 2014 8:31 PM
    Thursday, February 13, 2014 8:21 PM

Answers

  • Below is some C# example code. The key here is to make sure and get the formdigest value when you post. Secondly make sure the "type" is correct. SP.Data.TestlistListItem is the type name here. Please note, this type name is case sensitive. Even if you name your list testlist the type name must start with a capital letter. Also use the System.Web.Extensions to get the javascript serializer to make it easy to read the responses.

     public static string GetFormDigest()
     {
                string  formDigest = null;
                
                string resourceUrl = "http://basesmc15/_api/contextinfo";
                HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
                wreq.UseDefaultCredentials = true;
                wreq.Method = "POST";
                wreq.Accept = "application/json;odata=verbose";
                wreq.ContentLength = 0;
                wreq.ContentType = "application/json";
                string result;
                WebResponse wresp = wreq.GetResponse();
           
                using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
    
                var jss = new JavaScriptSerializer();
                var val = jss.Deserialize<Dictionary<string,object>>(result);
                var d = val["d"] as Dictionary<string, object>;
                var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
                formDigest = wi["FormDigestValue"].ToString();
    
                return formDigest;
               
    }
            
    public static void UpdateListItem()
    {
                string result = string.Empty;
                Uri uri = new Uri("http://basesmc15/_api/web/lists/getbytitle('testlist')/items(1)");
                HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
                wreq.Credentials = CredentialCache.DefaultNetworkCredentials;
                
                wreq.Method = "POST";
                wreq.Accept = "application/json; odata=verbose";
                wreq.ContentType = "application/json; odata=verbose";
                wreq.Headers.Add( "X-HTTP-Method","MERGE");
                wreq.Headers.Add(  "IF-MATCH", "*");
                wreq.Headers.Add("X-RequestDigest",GetFormDigest());
    
                string stringData = "{'__metadata': { 'type': 'SP.Data.TestlistListItem' }, 'Title': 'whatever'}";
                wreq.ContentLength = stringData.Length;
                StreamWriter writer = new StreamWriter(wreq.GetRequestStream());
                writer.Write(stringData);
                writer.Flush();
    
                WebResponse wresp = wreq.GetResponse();
                using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
    
       
    }


    Blog | SharePoint Field Notes Dev Tools | SPFastDeploy | SPRemoteAPIExplorer

    • Marked as answer by MSDN Student Wednesday, February 19, 2014 4:29 PM
    Saturday, February 15, 2014 3:32 AM

All replies

  • You can take a look at this MSDN article:

    http://msdn.microsoft.com/en-us/library/office/jj164022.aspx#WritingData


    -- Ilya

    Thursday, February 13, 2014 10:17 PM
  • Below is some C# example code. The key here is to make sure and get the formdigest value when you post. Secondly make sure the "type" is correct. SP.Data.TestlistListItem is the type name here. Please note, this type name is case sensitive. Even if you name your list testlist the type name must start with a capital letter. Also use the System.Web.Extensions to get the javascript serializer to make it easy to read the responses.

     public static string GetFormDigest()
     {
                string  formDigest = null;
                
                string resourceUrl = "http://basesmc15/_api/contextinfo";
                HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
                wreq.UseDefaultCredentials = true;
                wreq.Method = "POST";
                wreq.Accept = "application/json;odata=verbose";
                wreq.ContentLength = 0;
                wreq.ContentType = "application/json";
                string result;
                WebResponse wresp = wreq.GetResponse();
           
                using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
    
                var jss = new JavaScriptSerializer();
                var val = jss.Deserialize<Dictionary<string,object>>(result);
                var d = val["d"] as Dictionary<string, object>;
                var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
                formDigest = wi["FormDigestValue"].ToString();
    
                return formDigest;
               
    }
            
    public static void UpdateListItem()
    {
                string result = string.Empty;
                Uri uri = new Uri("http://basesmc15/_api/web/lists/getbytitle('testlist')/items(1)");
                HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
                wreq.Credentials = CredentialCache.DefaultNetworkCredentials;
                
                wreq.Method = "POST";
                wreq.Accept = "application/json; odata=verbose";
                wreq.ContentType = "application/json; odata=verbose";
                wreq.Headers.Add( "X-HTTP-Method","MERGE");
                wreq.Headers.Add(  "IF-MATCH", "*");
                wreq.Headers.Add("X-RequestDigest",GetFormDigest());
    
                string stringData = "{'__metadata': { 'type': 'SP.Data.TestlistListItem' }, 'Title': 'whatever'}";
                wreq.ContentLength = stringData.Length;
                StreamWriter writer = new StreamWriter(wreq.GetRequestStream());
                writer.Write(stringData);
                writer.Flush();
    
                WebResponse wresp = wreq.GetResponse();
                using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
    
       
    }


    Blog | SharePoint Field Notes Dev Tools | SPFastDeploy | SPRemoteAPIExplorer

    • Marked as answer by MSDN Student Wednesday, February 19, 2014 4:29 PM
    Saturday, February 15, 2014 3:32 AM
  • I couldn't get the upload to work until I added

    wreq.Headers.Add("Authorization", "BEARER" + formDigest);

    to Steve.Curran's code example.

    So just a heads up for anyone who also keeps getting an unexpected 403 Unauthorized!


    • Edited by Muldrr Monday, August 10, 2015 12:40 PM
    • Proposed as answer by Erik van Dongen Friday, April 20, 2018 2:05 PM
    Monday, August 10, 2015 12:39 PM
  • I couldn't get the upload to work until I added

    wreq.Headers.Add("Authorization", "BEARER" + formDigest);

    to Steve.Curran's code example.

    So just a heads up for anyone who also keeps getting an unexpected 403 Unauthorized!


    This last addition absolutely saved my day! Now I finally got it work! Many, many thanks!
    Friday, April 20, 2018 2:05 PM