Creating and Consuming WCF Web Service in ASP.Net


This article is written to provide an overview and samples for creating your own Web Service for letting your devices connect and communicate over a network (including the internet) with each other, store the data in one place, access and manage the entire database in one place and do various tasks.
The Internet of Things is a concept and phenomenon used to connect the hardware of your house or office over a beloved communication connection, including the nework called the "Internet". This article will provide an overview for you of how to create your own Web Service and create and manage clients that would be the devices sending the data to your service. Allow them to send the data to your service, then manage the data and then save it or perform any other service depending on the data.
By the end, you will be able to create a simple (or even the enterprise level; if you get the understanding and are willing to create a system of) web service that can run devices connected to it through the Internet and ohter networks. No matter what device is calling the service and in which protocol the service is being called, the server would respond and your services would be invoked and ran.

Internet of Things Service

The Internet of Things provides us with some services that can be used in managing and performing various tasks, depending on the data that was sent to us. You can think of a service like, "start the bulb when it is 6:00AM". Seems fair?
Similar as well as different tasks are done using the Internet of Things. The Internet of Things itself is a concept of connecting devices, more like household appliances, to each other through a common network, the "Internet". From where, they send/receive data from each other and perform the tasks assigned to them. In the preceding example, if the clock ticks 6:00 in the morning, the message is sent to the bulb for lighting up. I agree this is a bit of an exaggeration.
Creating a service
You create a service where you tell the devices to perform a task when a command is ed down to them. Usually a common hub or host takes a control and each device sends the data to the hub and then the hub decides what to do and from which devices to take the work. A hub acts like a server; it accepts requests, sends responses and then the clients (devices) perform their tasks. Thus, everything seems to work "magically".
Since only one hub is acting as the server, the service is installed on the hub. Each device connects to it to transmit the data and the hub manipulates the data and executes a service. The service is connected to any device connected and thus that device gets a trigger for its job.

Web Service

A Web Service is a service (a service can be a method) defined to be executed among more than one devices connected to each other using the internet. This is a method, to control the working of the devices connected to the network.
Not only houses, offices but many giants are also using this service to control their data from each and every device. This provides a better methodology to control the data and the functions being performed by each and every device. You can think of a security service in companies. "If the thumb fingerprint pattern is OK, open the door". This is a service, it depends how people apply it.
Interaction of the devices among each other can be done using many protocols and mechanisms. You can use SOAP, HTML and many more for sending the data and commands to the devices. You can send the data in the format of XML too.
WCF is a new technology provided by Microsoft that allows the devices to communicate and send the Metadata over HTML, SOAP, WSDL, XML Schema and WS-Policy. REST services, JSON is also usable.
It is of a good importance that the Web Service must be made secure so that anything unauthorized can be made invalid and only authorized devices and clients can communicate with the hub. SSL and some other standards can be used to set up the security for the devices.
A best software service is the one that you can always change and make suitable for your needs. If the software cannot be changed and customized to make it more secure and more efficient then the software is of no good.
A Web Service must respond to each and every request that has been sent to it.
WCF is one of the new foundations in the Web Services world and was introduced by Microsoft. It can be hosted in a console application or in IIS and can be accessed using Console applications, WPF applications or even websites. This makes it a good fit for today's needs. In this article we will be creating a Web Service that will be hosted in a Console Application and we will use that service using a website to provide an overview of the concept "Internet" connection.

Creating a Web Service

The first step is to create a web service. A Web Service is actually just a bunch of methods and functions that are executed whenever a client visits and asks the services to do something or get something. Don't get accustomed to the fancy name "Web Service", it is just a bunch of methods. Similar to a website or other software, you will be able to create functions, create properties, classes and objects.
Our Web Service: A service that provides an interface to the user to enter a data in the service and the service saves that data. The service also looks in for any present data, if the data is present it is shown otherwise nothing is shown instead of a form to enter the data.
You can make it more complex and add more functionalities to it to create an enterprise-level Web Service to be fully capable of performing the tasks.
Template of the Service
A Service needs to be an interface, why? Because when you need to be calling the service from the client, you don't need to tell him each and every step you're going through and every task you perform. Take an example of going to your fortune company and giving them an application, the company would just tell you "Application under review", the underlying processes like, "Boss waiting for Application", "Boss reviewing it", "Boss calling secretory to call the employee" and so on.
This is why, you will just create a signature of the actual service so that once ing it down to the client, the client only asks you to "I want to get a job" and then expects a result "Job given" or "Not qualified enough" only.
Create a Class Library in Visual Studio and name it WebServices_Interfaces and add references to the libraries required. Once done, add the following code to it. The ISaveData is an interface.
  1. // Add the references; must also be added to the Project  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  8. // Required and added  
  9. using System.ServiceModel;  
  10. using System.Runtime.Serialization;  
  12. // Name of this Class Library Project = WebServices_Interfaces  
  13. namespace WebServices_Interfaces  
  14. {  
  15.     // Following are the ServiceContracts  
  16.     [ServiceContract]  
  17.     public interface ISaveData  
  18.     {  
  19.         [OperationContract]  
  20.         void AddData(Data s);  
  22.         [OperationContract]  
  23.         Data[] GetCurrentData();  
  24.     }  
  26.     // DataContracts for the Web Service  
  27.     [DataContract]  
  28.     public class Data  
  29.     {  
  30.         private string text;  
  32.         [DataMember]  
  33.         public string DataLabel  
  34.         {  
  35.             set { this.text = value; }  
  36.             get { return this.text; }  
  37.         }  
  38.     }  
  39. }  
Creating a source for the Data
You can however, if you want, continue running the service in its environment for ever and keep the data that is attached to it in the memory or if you want, you can use your storage device to store the data coming to the service and that goes from the service in one place.
Create a new library and this time, name it WebServices_DataSources. Add the references to the libraries and add a new Class file called "DataSource". Once done, the following would be the code inside your file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  7. // Add this reference, for working with Files  
  8. using System.IO;  
  10. namespace WebServices_DataSources  
  11. {  
  12.     public class DataSource  
  13.     {  
  14.         // Get the current users MyDocuments folder  
  15.         static string directory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  
  16.         // Our File Name. You can change it in your project.  
  17.         static string fileName = "/myServiceFile.txt";  
  19.         // static variable  
  20.         // Will contain the content, for accessing and saving the data  
  21.         static List<string> currentData = File.ReadAllLines(directory + fileName).ToList();  
  23.         // This method saves the Data sent  
  24.         public void Save(string dataLabel)  
  25.         {  
  26.             currentData.Add(dataLabel);  
  27.             Directory.CreateDirectory(directory);  
  28.             File.Create(directory + fileName).Close();  
  30.             File.WriteAllLines(directory + fileName, currentData);  
  31.         }  
  33.         // Gets the current list.  
  34.         public List<string> GetDataList()  
  35.         {  
  36.             return currentData;  
  37.         }  
  38.     }  
  39. }  
Implementing the Service in your Application
The next step is to implement the service in an application that can be used and would contain the methods for your actual Web Service. You can see the Interface however only contains the signatures for your web service. This would serve as the actual web service and will be reached our by the devices each time they need to save the data.
Create a new library, add references to your WebServices_Interfaces and WebServices_DataSources that are required by your web service to use. Name this library project to be WebServices_Service and this class would implement the ISaveData interface, so that you can add the body to the signatures the interface has.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  7. // add the projects in this project  
  8. using WebServices_DataSources;  
  9. using WebServices_Interfaces;  
  12. namespace WebServices_Service  
  13. {  
  14.     // Implements the ISaveData  
  15.     public class WebService : ISaveData  
  16.     {  
  17.         // Adds the Body to the methods  
  18.         public void AddData(Data d)  
  19.         {  
  20.             DataSource ds = new DataSource();  
  21.             ds.Save(d.DataLabel);  
  22.         }  
  24.         public Data[] GetCurrentData()  
  25.         {  
  26.             DataSource sd = new DataSource();  
  27.             List<string> dataList = sd.GetDataList();  
  28.             Data[] dataArray = new Data[dataList.Count];  
  29.             for (int i = 0; i < dataList.Count; i++)  
  30.             {  
  31.                 Data s = new Data();  
  32.                 s.DataLabel = dataList[i];  
  33.                 dataArray[i] = s;  
  34.             }  
  35.             return dataArray;  
  36.         }  
  37.     }  
  38. }  
You can see, this code has the actual job of the service, when you call AddData you can see that it actually adds the data in the DataSource and upon GetCurrentData it gets the data from the DataSource and returns it to the user. The user can then use it to perform other tasks.
Hosting your Web Service
You've created the application, good. But how are others going to use it when you're not going to set any location for it to be present at? Think of it as a bag of money, but you've no idea where it is.
You can host your web service in nearly any application, from Console to Web Applications. But since this article seems to provide an overview I will cover this topic using a Console Application that will continue running and hosting the application. The Console would accept all of the requests being made to it, you can set a URI for the resources and the console would serve as a server at that location.
Create a Console application, add the references to our three libraries and then add the following code to the Program.cs file created in your application. Name.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  7. // add the references to the libraries required.  
  8. using WebServices_Interfaces;  
  9. using WebServices_Service;  
  10. using WebServices_DataSources;  
  11. using System.ServiceModel;  
  12. using System.ServiceModel.Description;  
  14. namespace WebServices_HostingAndRunning  
  15. {  
  16.     class Program  
  17.     {  
  18.         static void Main(string[] args)  
  19.         {  
  20.             // the Uri for this Web Service.  
  21.             Uri baseAddress = new Uri("http://localhost:8080/My_WebService");  
  23.             // Create the ServiceHost.  
  24.             using (ServiceHost host = new ServiceHost(typeof(WebService), baseAddress))  
  25.             {  
  26.                 // Enable metadata publishing.   
  27.                 ServiceMetadataBehavior smb = new ServiceMetadataBehavior();  
  28.                 smb.HttpGetEnabled = true;  
  29.                 smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;  
  30.                 host.Description.Behaviors.Add(smb);  
  32.                 // Open the ServiceHost to start listening for messages. Since  
  33.                 // no endpoints are explicitly configured, the runtime will create  
  34.                 // one endpoint per base address for each service contract implemented  
  35.                 // by the service.  
  36.                 host.Open();  
  38.                 Console.WriteLine("The service is ready at {0}", baseAddress);  
  39.                 Console.WriteLine("Press <Enter> to stop the service.");  
  40.                 Console.ReadLine();  
  42.                 // Close the ServiceHost.  
  43.                 host.Close();  
  44.             }  
  45.         }  
  46.     }  
  47. }  
Note: The preceding code was captured using MSDN's document. That document has more code for hosting the applications in managed applications.
Configuring your web service server
Your console application has an App.Config file that can be used to configure its properties and set some properties to it. Edit it, or replace it with the following code:
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.     <startup>   
  4.         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  5.     </startup>  
  6.   <!-- Server Configuration is as following -->  
  7.   <system.serviceModel>  
  8.     <services>  
  9.       <service name="WebServices_Service.WebService">  
  10.         <!-- baseAddress and the Interface of the Service is added.  -->  
  11.         <endpoint  
  12.                 address="http://localhost:8080/My_WebService"   
  13.                 binding="wsHttpBinding"   
  14.                 contract="WebServices_Interfaces.ISaveData" />  
  15.       </service>  
  16.     </services>  
  17.   </system.serviceModel>  
  18. </configuration>  
You can now run your application. Usually you're going to get an error saying it was not able to get the Uri http://+:8080 something like this. Don't worry, just close Visual Studio, re-run Visual Studio in Administrator mode and re-run the application, this time it will run and will show the message saying the service is running at the {baseAddress}. You can always change the baseAddress for your application.
The serving of the Metadata is also necessary, don't remove that code. the service won't be usable if you remove that part.
web service server  

Creating a Client

The client is the device or a program that consumes the service that you've created. You can use a website as a service client, or an application developed as a console or Windows Forms to consume your web service and communicate with other devices.
In our project, we will create a website to consume the web service. This web site will provide an interface to the user where he can enter data (text) and submit to add the data, he can also view the currently added data to the storage devices.
Create a Website
You should first create a website. You don't need to worry about creating a website or web application using MVC, Windows Forms and so on. Just create a website, I used an ASP.NET StarterSite (Empty CSHTML) website.
To use the service, you will be required to add the references to your service. But first add the references to the System.ServiceModel. Once done, add the reference to your libraries.
Adding a reference to the Service is a tricky part here, you need to right-click on the App_WebReferences folder (where all of the service references are present); if the folder isn't present, create it because it is initially not created and then select Add Service Reference. The pop-up would generate for you, to enter the Uri for the service. At this stage before continuing, you need to ensure that your service is running (you need to ensure the Console Application is running, and the message saying Web Service is running at {baseAddress}). You can enter the URI and continue. It will automatically find the web service and will add the required code and files for using the services.
Create a Website 
Now your folder will have files as in this hierarchy:
Creating a landing page
Now once these things are done, you can create a good looking home page to land the user (client) on. Where he will be able to find a form to send the data to the service.
Remember: The service must be running, otherwise an exception will be raised that nothing was found to capture the request.
This page is just for the sake of letting the user understand the interface, if you're creating the service application for devices where you don't want to create any form. You can simply get the data from the requests that the device makes and get the data associated with the request.
  1. @using System.ServiceModel;  
  2. @using WebServices_Interfaces;  
  4. @{  
  5.     List<string> currentData = new List<string>();  
  6.     // Enroll the student  
  8.     if (IsPost)  
  9.     {  
  10.         using (ChannelFactory<ISaveData> myServiceProxy =  
  11.         new ChannelFactory<ISaveData>("My_WebService_EndPoint"))  
  12.         {  
  13.             myServiceProxy.Open();  
  14.             ISaveData saveDataService = myServiceProxy.CreateChannel();  
  15.             // Create the Instance...  
  16.             Data s = new Data();  
  18.             // Get the Text  
  19.             s.DataLabel = Request["text"];  
  20.             saveDataService.AddData(s);  
  21.             myServiceProxy.Close();  
  22.         }  
  23.     }  
  25.     // Load the data from the Server  
  26.     using (ChannelFactory<ISaveData> myServiceProxy =  
  27.     new ChannelFactory<ISaveData>("My_WebService_EndPoint"))  
  28.     {  
  29.         myServiceProxy.Open();  
  31.         // Create the Channel for the Client to work from  
  32.         ISaveData getDataService = myServiceProxy.CreateChannel();  
  34.         // Get the current Data  
  35.         Data[] savedData = getDataService.GetCurrentData();  
  37.         // Work on Each of the Data  
  38.         foreach (Data data in savedData)  
  39.         {  
  40.             // Add the data to the List (Look in the first line)  
  41.             currentData.Add(data.DataLabel);  
  42.         }  
  43.         // Close the service proxy  
  44.         myServiceProxy.Close();  
  45.     }  
  46. }  
  48. @{  
  49.     Layout = "~/_SiteLayout.cshtml";  
  50.     Page.Title = "Home Page";  
  51. }  
  53. <ul>  
  54.     @if (currentData.Count > 0)  
  55.     {  
  56.         <p>Current data in the file is as: </p>  
  57.         // if there is any content present, then  
  58.         foreach (string str in currentData)  
  59.         {  
  60.             // Write those data.  
  61.             <li>@str</li>  
  62.         }  
  63.     }  
  64. </ul>  
  66. <div>  
  67.     <p>Use the following form to add the content.</p>  
  68.     <form method="post">  
  69.         <input type="text" name="text" />  
  70.         <input type="submit" value="Submit" />  
  71.     </form>  
  72. </div>  
Initially the page wouldn't contain anything but just a form since there is no data in the backend file that we're having right now. A using is used when you're using any resources, to trigger .NET's functionality to clean and flush the resources.
What happens when the user triggers the Submit
When the user hits the submit button, the website makes a request to the Web Service (that is currently being hosted and run in the Console Application and it must be running) and executes the function to save the data. This is only present if the request is a POST HTTP request. When the user submits the form, the form, along with the text data, is submitted to the server (web service) and there the function is executed to save the data (in the text file).
If the request is not a POST of a simple request then the preceding code block would not execute and nothing will be saved, however the GET function would still execute and cause the web service to return the currently available data in the storage medium.
So, if there is any data present the page would like this.
data present 
The data in the file is like this:
data in the File 
Points of Interest
WCF is the best method to use when creating a Web Service, it runs on your Windows OS since it is developed on the .NET framework. You can send requests and get responses in SOAP, REST and many more. XML, JSON and other syntaxes are supported in it. You can host this service in any application and get any device as its client.

Similar Articles