6

I have a requirement to create list item in a sharepoint online list using the REST API and c#. How to achieve this. Most of the article show using REST API in jquery and Javascript but I have a requirement to do this using c#. Please suggest if anyone have one with this problem.

Unfortunately, I am not getting any code sample for that.

Any kind of help will be appreciated. Thanks

  • What kind of Visual Studio project are you building? – Rob Windsor Dec 13 '13 at 18:14
4

Check out this MSDN article which might help you out. Here's Microsoft's example code for adding a single item to a list (title field only):

//Execute a REST request to get the form digest. All POST requests that change the state of resources on the host
//Web require the form digest in the request header.
HttpWebRequest contextinfoRequest =
    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/contextinfo");
contextinfoRequest.Method = "POST";
contextinfoRequest.ContentType = "text/xml;charset=utf-8";
contextinfoRequest.ContentLength = 0;
contextinfoRequest.Headers.Add("Authorization", "Bearer " + accessToken);

HttpWebResponse contextinfoResponse = (HttpWebResponse)contextinfoRequest.GetResponse();
StreamReader contextinfoReader = new StreamReader(contextinfoResponse.GetResponseStream(), System.Text.Encoding.UTF8);
var formDigestXML = new XmlDocument();
formDigestXML.LoadXml(contextinfoReader.ReadToEnd());
var formDigestNode = formDigestXML.SelectSingleNode("//d:FormDigestValue", xmlnspm);
string formDigest = formDigestNode.InnerXml;

//Execute a REST request to get the list name and the entity type name for the list.
HttpWebRequest listRequest =
    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists(guid'" + listId + "')");
listRequest.Method = "GET";
listRequest.Accept = "application/atom+xml";
listRequest.ContentType = "application/atom+xml;type=entry";
listRequest.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse listResponse = (HttpWebResponse)listRequest.GetResponse();
StreamReader listReader = new StreamReader(listResponse.GetResponseStream());
var listXml = new XmlDocument();
listXml.LoadXml(listReader.ReadToEnd());

//The entity type name is the required type when you construct a request to add a list item.
var entityTypeNode = listXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:ListItemEntityTypeFullName", xmlnspm);
var listNameNode = listXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:Title", xmlnspm);
string entityTypeName = entityTypeNode.InnerXml;
string listName = listNameNode.InnerXml;

//Execute a REST request to add an item to the list.
string itemPostBody = "{'__metadata':{'type':'" + entityTypeName + "'}, 'Title':'" + newItemName + "'}}";
Byte[] itemPostData = System.Text.Encoding.ASCII.GetBytes(itemPostBody);

HttpWebRequest itemRequest =
    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists(guid'" + listId + "')/Items");
itemRequest.Method = "POST";
itemRequest.ContentLength = itemPostBody.Length;
itemRequest.ContentType = "application/json;odata=verbose";
itemRequest.Accept = "application/json;odata=verbose";
itemRequest.Headers.Add("Authorization", "Bearer " + accessToken);
itemRequest.Headers.Add("X-RequestDigest", formDigest);
Stream itemRequestStream = itemRequest.GetRequestStream();

itemRequestStream.Write(itemPostData, 0, itemPostData.Length);
itemRequestStream.Close();

HttpWebResponse itemResponse = (HttpWebResponse)itemRequest.GetResponse();
RetrieveListItems(accessToken, listId);

Instead of using an "access token" variable like accessToken, you can likely use SharePoint credentials instead, like in this example.

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

1

At least the following components could be utilized for that purpose:

You might find this post helpful that demonstrates how to consume SharePoint REST API in .NET, in particular it demonstrates how to:

  • perform authentication in SharePoint Online using HttpClient
  • perform basic CRUD operations using HttpClient

See SPHttpClient class implementation that derives from HttpClient class for a details.

The following example demonstrates how to create a List Item:

using (var client = new SPHttpClient(webUri, userName, password))
{
    var itemPayload = new { __metadata = new { type = "SP.Data.TasksListItem" }, Title = "Approval Task" };
    var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items",webUri,listTitle);
    var item = client.ExecuteJson(endpointUrl, HttpMethod.Post, null, itemPayload);
    Console.WriteLine("Task '{0}' has been created successfully",item["Title"]);
}
0

If you know how to do it using REST/Js/jQuery, one of the possible way could be create the request with the help of Fiddler and pass that over to SP using WebRequest using C# application.

  • Yes, this is correct. The REST API will be consistent among platforms and languages. I think you just need to learn how to invoke ANY REST API via c# and then you will be on your way. Look for any C# REST tutorial and you should be good. – tyshock Dec 13 '13 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.