C# Call SharePoint Web API from Server Object Model

In my last blog SharePoint 2013 Create and Host Web Service. I have explained how to create SharePoint Web Service. So we need to consume that service. We can consume that service from JSOM as well as SSOM. Here I am explaining how we can consume web service from C# code(SSOM).

So first of all we need to define same entity for getting data, Which we had used in operation contract of service. So below is an example of entity.

a. Entity in Service Contract

    [DataContract]
    public class ModuleDetails
    {
        [DataMember]
        public string ID { get; set; }

        [DataMember]
        public string ModuleName { get; set; }

        [DataMember]
        public string AppName { get; set; }
    }


b. Entity where we will consume that service

    public class ModuleDetails
    {
        public string ID { get; set; }
        public string ModuleName { get; set; }
        public string AppName { get; set; }
    }


1. If request type is Get

                        System.Net.WebClient client = new System.Net.WebClient();

                        client.Headers.Add("Authorization", "Your authorization token");
                        string detailsjson = Encoding.ASCII.GetString(client.DownloadData(APIurl));

                        JavaScriptSerializer j = new JavaScriptSerializer();
                        List<ModuleDetails> det = j.Deserialize<List<ModuleDetails>>(detailsjson);

2. If request type is Post 

                        System.Net.WebClient client = new System.Net.WebClient();
                        client.Headers.Add("Authorization", "Your authorization token");
                        client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
                        string data = "{\"ModuleId\":\"" + moduleId + "\",\"ModuleName\":\"" + moduleName + "\",\"EmailAddress\":\"" + emailAddress + "\",\"Message\":\"" + textMessage + "\",\"CreationDateAndTime\":\"" + Date + "\"}";
                        detailsjson = Encoding.ASCII.GetString(client.UploadData(APIurl, "POST", Encoding.Default.GetBytes(data)));

JavaScriptSerializer j = new JavaScriptSerializer();
                        List<ModuleDetails> det = j.Deserialize<List<ModuleDetails>>(detailsjson);

Comments

  1. I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete

Post a Comment

Popular posts from this blog

C# Copy files from one server to another

Suppress StyleCop SA1600

Telerik Rad Grid Sorting