Consume a SharePoint 2013 Online REST feed using .NET managed code

In this post, we’ll see how we can consume a SharePoint 2013 online REST feed using managed c# code. I’d be using a Provider Hosted App template in Visual Studio 2013 for this demonstration. It is very straight forward to consume a Restful .NET service by issuing HttpWebRequest from c# code and getting HttpWebResponse.

I will be invoking https://yoursite.sharepoint.com/_api/web/lists from c# code to get the list of SharePoint lists in this Office 365 site. The following screenshot shows the response for this Restful service in the browser.

image

Now let’s start creating a Provider hosted app project in Visual Studio 2013.

File –> New Project –> Visual C# –> Office/SharePoint –> App for SharePoint 2013 and name it as ‘ReadRESTCSharp’ & set the site for debugging and app type as ‘Provider-hosted’.

image

Specify the web project type as ‘ASP.NET Web Forms Application’. In the next step, Visual Studio 2013 would prompt for setting App Authentication Type, I did not see this option while using Visual Studio 2012 to create Provider hosted apps.

image

Set the App authentication type as ‘Use Windows Azure Access Control Service’ (mentioned in the above screenshot).

Click ‘Finish’ to create the app.

Go to  ASP.NET Web Forms project and open the default.aspx.cs

Import the following three namespaces at the top.

using Microsoft.SharePoint.Client;
using System.Net;
using System.IO;

In page_load comment out the following lines of code.

//var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            //using (var clientContext = spContext.CreateUserClientContextForSPHost())
            //{
              //  clientContext.Load(clientContext.Web, web => web.Title);
               // clientContext.ExecuteQuery();
                //Response.Write(clientContext.Web.Title);
            //}

Since I’m using my own developer tenant in Office 365, I would want to trust all the certificates issued by SharePoint Online to my browser. Otherwise, it will keeping popping up a message to trust the certificates in Visual Studio 2013, when I hit F5 and debug the app.

Open the TokenHelper.cs and the add the following static method ‘TrustAllCertificates’

public static void TrustAllCertificates()
        {
            //Trust all certificates
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                ((sender, certificate, chain, sslPolicyErrors) => true);
        }

If you are using Visual Studio 2012, it adds ‘TrustAllCertificates’ in TokenHelper.cs by default.

I will be using my Office 365 developer tenant for this demo, which forces the need to get the Access Token from Office 365 and pass it as a part of the header in the HttpWebRequest. First I need to get the ContextTokenString by invoking GetContextTokenFromRequest method in TokenHelper.cs. Then I need to get the actual SharePointContextToken by invoking ReadAndValidateContextToken method in the TokenHelper.cs. Finally I need to get AccessToken by invoking the GetAccessToken method in the TokenHelper.cs. I won’t go too detailed about this one. All the dynamics of the Token exchange is covered in one of my previous article.

Once the AccessToken is received, a HTTPWebRequest needs to be issued by setting the AccessToken with Bearer, also we need to set the HTTPRequest method as ‘GET’ and HTTPRequest accept headers as “application/json;odata=verbose”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Microsoft.SharePoint.Client;

namespace ReadRESTCSharpWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Uri redirectUrl;
            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
                case RedirectionStatus.Ok:
                    return;
                case RedirectionStatus.ShouldRedirect:
                    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    Response.Write("An error occurred while processing your request.");
                    Response.End();
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
            // The following code gets the client context and Title property by using TokenHelper.
            // To access other properties, the app may need to request permissions on the host web.
            //var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            //using (var clientContext = spContext.CreateUserClientContextForSPHost())
            //{
              //  clientContext.Load(clientContext.Web, web => web.Title);
               // clientContext.ExecuteQuery();
                //Response.Write(clientContext.Web.Title);


            //}

            TokenHelper.TrustAllCertificates();

            //Get the ContextTokenString
            string ContextTokenString = TokenHelper.GetContextTokenFromRequest(Request);



            if (ContextTokenString != null)
            {

                //Get the SharePointContextToken
                SharePointContextToken ContextToken = TokenHelper.ReadAndValidateContextToken(ContextTokenString, Request.Url.Authority);

                Uri sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);

                //Get the AccessToken
                string AccessToken = TokenHelper.GetAccessToken(ContextToken,sharepointUrl.Authority).AccessToken;

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(@"https://yoursite.sharepoint.com/_api/web/lists");
                request.Method = "GET";
                request.Accept = "application/json;odata=verbose";
                request.Headers.Add("Authorization", "Bearer " + AccessToken);

                HttpWebResponse response =(HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());

                Response.Write("<h2>List of SharePoint lists in SharePoint Online fetched from managed code</h2>");
                Response.Write("<p>" + reader.ReadToEnd() + "</p>");
                Response.Flush();
            
            
            }




        }
    }
}

After executing the above we get the successful HTTPResponse which can be seen in debug mode in Visual Studio 2013.

image

  Subscribe to my blog

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *


two × 6 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>