Basics Of WCF Service With Hosting And Consuming Using ASP.NET

Description: In this tutorial, we will learn:

  • How to create a WCF Service
  • How to create Service Endpoints
  • How to Host the Service over IIS
  • How to Consume the service using ASP.NET Web application

Step 1: First, open Visual Studio (any version) and Create a new Class Library project.

 

Step 2: Once the project gets created, delete the Class1.cs file which is auto-generated.

 

Step 3: Right click on the Project Name and Add a WCF Service.

 

 

Step 4: Once the WCF Service is added to the project, it will add two types of files, as mentioned below.



As you can see above, the System.ServiceModel is added to the reference libraries, as this is the main .NET assembly which supports WCF Services. So, it is a must.

Step 5: First, open IDemoService.cs file and replace the code with the below mentioned code.
  1. using System.ServiceModel;  
  2.    
  3. namespace DemoWCFService  
  4. {  
  5.     [ServiceContract] //Till will tells the class file that this is a WCF Service  
  6.     public interface IDemoService  
  7.     {  
  8.         [OperationContract] //This will expose the Operations that can be operated using this WCF Service  
  9.         string GetResponse(); //This is the Method name implementation.   
  10.     }  
  11. }  

As you can see above, the System.ServiceModel is referenced in it using statements.

IDemoService interface is decorated with the [ServiceContract] attribute which tells the project that this is a WCF Service.

GetResponse() is a custom method which returns string and it is also decorated with [OperationContract] attribute, which tells that this method can be consumed by client.

Step 6: Open DemoService.cs file and replace the code with the below mentioned code.

  1. namespace DemoWCFService  
  2. {  
  3.     public class DemoService : IDemoService  
  4.     {  
  5.         string IDemoService.GetResponse() => "This is the Response from WCF Service.";  
  6.     }  
  7. }  
As it is very simple to understand that the method we have declared in the Interface file is implemented here and it is returning the simple text.
 

Step 7: Now, comes the main concept i.e. Endpoints.

Endpoints are the access points for the client applications to access the WCF Service for request and response functionality. They have three main properties:

  • Address: It tells at which location the service is hosted.
  • Type of Binding: It specifies in which format the data is to be exchanged.
  • Contract: It is actually used to specify the interface name that we have just created. It tells which methods are accessible to the client.
  1. <configuration>  
  2.     <system.serviceModel>  
  3.         <behaviors>  
  4.             <serviceBehaviors>  
  5.                 <behavior name="mexBehaviour">  
  6.                     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />  
  7.                     <serviceDebug includeExceptionDetailInFaults="false" />  
  8.                 </behavior>  
  9.             </serviceBehaviors>  
  10.         </behaviors>  
  11.         <services>  
  12.             <service name="DemoWCFService.DemoService" behaviorConfiguration="mexBehaviour">  
  13.                 <endpoint address="" binding="basicHttpBinding" contract="DemoWCFService.IDemoService">  
  14.                     <identity>  
  15.                         <dns value="localhost" />  
  16.                     </identity>  
  17.                 </endpoint>  
  18.                 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />  
  19.                 <host>  
  20.                     <baseAddresses>  
  21.                         <add baseAddress="http://localhost:8733/DemoWCFService/DemoService/" />  
  22.                     </baseAddresses>  
  23.                 </host>  
  24.             </service>  
  25.         </services>  
  26.     </system.serviceModel>  
  27. </configuration>  

You will find a file named app.config. The above code is to be pasted in that file. If you are using Visual Studio 2013 and above, this file with this code will be auto-generated; but not in the earlier versions.

Now, let’s have a look at the app.config file code.

  • In the behaviors element, you can see that a tag name serviceMetadata is added. This tag allows the MetaData of the service to be available to the client in the form of WSDL document. If you wish to know what is WSDL document, I will explain that in a later tutorial. For now, think it to be a document which shares data to the client.
  • In the services tag, we have named the service which is the combination of namespace of class file followed by classname.
  • Then, we have specified endpoint (explained above). The address property has been left blank, but you can give it any meaningful name. The binding is basic HTTP binding and the contract name is the name of the interface. Identity element is used to specify that we want to host the service at localhost (means using IIS).
  • Another endpoint is being mentioned which allows WSDL document to be generated.
  • Then, in the host address, we have added the baseAddress as localhost, followed by the port number of local system.

Now, we have completed creating our service. Now, we need a hosting application which will host it over HTTP Protocol.

Step 8: Now, add a new Windows Console application project to the same solution.

 

 

Once the project is created, add a reference to System.ServiceModel assembly and the WCF Service project.

 





Now, open Program.cs file and replace the code with the below one.
  1. using System;  
  2. using DemoWCFService;  
  3. using System.ServiceModel;  
  4.    
  5. namespace DemoServiceHost  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             using (var host = new ServiceHost(typeof(DemoService)))  
  12.             {  
  13.                 host.Open();  
  14.                 Console.WriteLine("The Host Started Successfully at " + DateTime.Now);  
  15.                 Console.ReadLine();  
  16.             }  
  17.         }  
  18.     }  
  19. }  

In the above code, we have created the object of ServiceHost class and passed the type of service to its constructor. The rest of the code is self explanatory.

Now, in the App.config file, add the same code as that of the WCFService project’s App.config file, that we just discussed above.

Set this as Startup project and run the application using Ctrl + F5 keys together. A console window will open which confirms that your service is now hosted.

Now, its the time to consume that service in an ASP.NET Web application.

Step 9: Add a new ASP.NET Web Application project to the same solution.







Step 10: First thing to keep in mind is that the service host should be running to be consumed. So, please go to the folder of your Service host project and find the bin folder. There you will find exe file. Run that in the Administrator mode.



Step 11: Let's consume the WCF Service that we have created, to generate the proxy classes so that we can use them.

 

 

Step 12: Add a new Webform to the project and press f7 key to move to the source code file.

Add the following code to the Page_Load event.

  1. using System;  
  2. using DemoWCFServiceClient.DemoWCFServiceConsumer;  
  3.    
  4. namespace DemoWCFServiceClient  
  5. {  
  6.     public partial class index : System.Web.UI.Page  
  7.     {  
  8.         protected void Page_Load(object sender, EventArgs e)  
  9.         {  
  10.             var client = new DemoServiceClient();  
  11.             Response.Write(client.GetResponse());   
  12.         }  
  13.     }  
  14. }  
 

All you need to do is to add the Service proxy class in the using directive. In Page_Load() event, we create instance of the client, and the method of the WCF Service will be automatically visible to the instance, as shown in the above images.

Now, finally, you have consumed the service. Let's run the project and check if everything is fine. But before that, we need to do some settings to run the host and web application at the same time.

Just follow the below two steps,





Now, press Ctrl + f5 together and web page will load, and the response from WCF service will be displayed on the page as shown below.


If I missed something, please comment so that I can update; or give your valuable feedback and share.

Up Next
    Ebook Download
    View all
    Learn
    View all