User2012384
User2012384

Reputation: 4927

C# Add item to Sharepoint list using REST API

I would like to add an item to a list in sharepoint using below code:

protected string httpGetPost(string getPostMode, string url, string dataToPost = "")
{
    HttpWebRequest endpointRequest = (HttpWebRequest)WebRequest.Create(url);
    endpointRequest.Method = getPostMode;

    var credentialCache = new CredentialCache();
    credentialCache.Add(
      new Uri(endpointRequest.RequestUri.GetLeftPart(UriPartial.Authority)), // request url's host
      "Digest",  // authentication type 
      new NetworkCredential(userName, password) // credentials 
    );
    endpointRequest.Credentials = credentialCache;

    endpointRequest.Accept = "application/json;odata=verbose";
    endpointRequest.ContentType = "application/json;odata=verbose";

    if (!string.IsNullOrEmpty(dataToPost))
    {
        using (Stream dataStream = endpointRequest.GetRequestStream())
        {
            byte[] bs = Encoding.ASCII.GetBytes(dataToPost);
            dataStream.Write(bs, 0, bs.Length);
        }
    }
    using (var resp = endpointRequest.GetResponse())
    {
        var html = new StreamReader(resp.GetResponseStream()).ReadToEnd();
        return html;
    }
}

And call the above method using below code:

httpGetPost("POST", url, "{\"__metadata\": { \"type\": \"SP.Data.Test_x0020_ListListItem\" }, \"Title\": \"Test\", \"Column B\", \"BBB\"}");

Here's the data I'm posting:

{"__metadata": { "type": "SP.Data.Test_x0020_ListListItem" }, "Title": "Test", "Column B", "BBB"}

I've took a look at this website https://msdn.microsoft.com/en-us/library/office/dn292552.aspx, but the authorization is different, it's using an accesstoken, but here's the problem:

In this website: http://sharepoint.stackexchange.com/questions/69617/sharepoint-2013-oauth-url-to-get-token, it saids I can't get the accesstoken, so I used username and password to login the sharepoint, but here comes another problem:

A System.Net.WebException is thrown in var resp = endpointRequest.GetResponse(), the error is saying The remote server returned an error: (403) Forbidden.

The account is a domain admin as well as a sharepoint admin.

Why I'm still getting the 403 error?

For some reasons, I can only use the REST API to communicate with sharepoint.

Upvotes: 0

Views: 6776

Answers (1)

Arcan.NET
Arcan.NET

Reputation: 710

Here is a slightly different method to achieve your goals. Some of the objects are specific to Store Apps in this example, but they can all easily be replaced with other values in a standard app.

 public string digest()
 {
 String retVal = "";
 try
 {
 string url = "https://YourSite.com/";
 HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
 client.BaseAddress = new System.Uri(url);
 string cmd = "_api/contextinfo";
 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
 client.DefaultRequestHeaders.Add("ContentType", "application/json");
 client.DefaultRequestHeaders.Add("ContentLength", "0");
 StringContent httpContent = new StringContent("");
 var response = client.PostAsync(cmd, httpContent).Result;
 if (response.IsSuccessStatusCode)
 {
 string content = response.Content.ReadAsStringAsync().Result;
 JsonObject val = JsonValue.Parse(content).GetObject();
 JsonObject d = val.GetNamedObject("d");
 JsonObject wi = d.GetNamedObject("GetContextWebInformation");
 retVal = wi.GetNamedString("FormDigestValue");
 }
 }
 catch
 { }
 return retVal;
 }

 FileOpenPicker picker = new FileOpenPicker();
 picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 picker.ViewMode = PickerViewMode.Thumbnail;
 // Filter to include a sample subset of file types.
 picker.FileTypeFilter.Clear();
 picker.FileTypeFilter.Add(".bmp");
 picker.FileTypeFilter.Add(".png");
 picker.FileTypeFilter.Add(".jpeg");
 picker.FileTypeFilter.Add(".jpg");
 // Open the file picker.
 StorageFile path = await picker.PickSingleFileAsync();
 if (path != null)
 {
 string url = "https://YourSite.com/Subsite/";
 HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
 client.BaseAddress = new System.Uri(url);
 client.DefaultRequestHeaders.Clear();
 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
 client.DefaultRequestHeaders.Add("X-RequestDigest", digest());
 client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
 client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
 IRandomAccessStream fileStream = await path.OpenAsync(FileAccessMode.Read);
 var reader = new DataReader(fileStream.GetInputStreamAt(0));
 await reader.LoadAsync((uint)fileStream.Size);
 Byte[] content = new byte[fileStream.Size];
 reader.ReadBytes(content);
 ByteArrayContent file = new ByteArrayContent(content);
 HttpResponseMessage response = await client.PostAsync("_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?@TargetLibrary='Project Photos'&@TargetFileName='TestUpload.jpg'", file);
 response.EnsureSuccessStatusCode();
 if (response.IsSuccessStatusCode)
 { }
 }

Upvotes: 1

Related Questions