Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET

Create, Host (Self Hosting, IIS hosting) and Consume WCF Service

Rate me:
Please Sign up or sign in to vote.
4.72/5 (31 votes)
3 Feb 2011CPOL4 min read 200.6K   5.8K   93   25
Create, Host (Self Hosting, IIS hosting) and Consume WCF Service

What is WCF?

Windows Communication Foundation API allows to build distributed architecture in such manner that once created, service code can be utilized by the in-house application which using tcp/ip to communicate, web application using http protocol to communicate to web services, application using msmq. WCF Services also works with the application developed other than .NET Framework.

Create WCF Service

Follow the below listed step to create Service.

Step 1

Create service from Visual Studio. Select the go to C# or VB, then select project type WCF Service library or WCF service website project template.

Image 1

The first one creates the *.dll and app.config file after the compilation which you can then use in your host application and expose the service to clients.

Image 2

The second one creates the project with the proper web.config file and *.svc file which gets hosted on IIS via virtual directly and service gets exposed to client via HTTP protocol. So by that service cannot be exposed to Tclient. The benefit of this option is that there is no need to create host application you can directly host on IIS via virtual directory. For this discussion, first I am creating a WCF service library and then I am going to discuss about IIS deployment also.

Image 3

Step 2

Create contract by specifying proper attributes. This contract tells the client what are the methods that get exposed by the service and custom type exposed by the service. You can decorate your contract by the list of attributes in System.ServiceModel namespace. You can create your own files or after selecting proper project type, it creates two files for your Iservice.cs and Service.cs. If you are going to create your own files, it's recommended that you can create your interface and implement it in your class.

[ServiceContract] - defines the interface to participate in provided service.

C#
[ServiceContract]
public interface IService1
{
....
}

[OperationContract] - defines the method going to be exposed by the service.

C#
[OperationContract]
string GetData(int value);

[DataMember] - defines the property exposed via service.

C#
[DataMember]
public bool BoolValue
{
  get { return boolValue; }
  set { boolValue = value; }
}

[DataContract] - defines the custom data type exposed via service.

C#
[DataContract]
public class CompositeType
{
...
}

After you are done with the creation of the web service, your code should look as below.

Library app.config file

This file contains information about the metadata exchange defining endpoint of metadata. It also contains information about the endpoints where client talks with service. Endpoints are ABC means Address, Binding and Contract. As you see in the above config file service exposed for TCP communication by the following line:

XML
<system.serviceModel>
   <services>
     <service name="WcfServiceLibrary.Service1"
   behaviorConfiguration="WcfServiceLibrary.Service1Behavior">
       <host>
         <baseAddresses>
           <add baseAddress = "http://localhost:8080/Service1/" />
         </baseAddresses>
       </host>
       <!-- Service Endpoints -->
       <!-- Unless fully qualified,
       address is relative to base address supplied above -->
       <endpoint address="net.tcp://localhost:9000/myservice"
       binding="netTcpBinding" contract="WcfServiceLibrary.IService1">

       </endpoint>
       <endpoint address ="" binding="wsHttpBinding"
       contract="WcfServiceLibrary.IService1">
         <!--
             Upon deployment, the following identity element
        should be removed or replaced to reflect the
             identity under which the deployed service runs.
        If removed, WCF will infer an appropriate identity
             automatically.
         -->
         <identity>
           <dns value="localhost"/>
         </identity>
       </endpoint>
       <!-- Metadata Endpoints -->
       <!-- The Metadata Exchange endpoint is used by the service
   to describe itself to clients. -->
       <!-- This endpoint does not use a secure binding and
   should be secured or removed before deployment -->
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
     </service>
   </services>
   <behaviors>
     <serviceBehaviors>
       <behavior name="WcfServiceLibrary.Service1Behavior">
         <!-- To avoid disclosing metadata information,
         set the value below to false and remove the metadata endpoint
    above before deployment -->
         <serviceMetadata httpGetEnabled="True"/>
         <!-- To receive exception details in faults for debugging purposes,
         set the value below to true.  Set to false before deployment
         to avoid disclosing exception information -->
         <serviceDebug includeExceptionDetailInFaults="False" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>

Binding details: http://www.c-sharpcorner.com/UploadFile/pjthesedays/bindwcf05032009012251AM/bindwcf.aspx.

IService.Cs file

C#
namespace WcfServiceLibrary
{
    // NOTE: If you change the interface name "IService1" here, 
    // you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
 
 
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
 
 
        // TODO: Add your service operations here
    }
 
    // Use a data contract as illustrated in the sample below to add 
    // composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";
 
 
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
 
 
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

Service.cs

C#
namespace WcfServiceLibrary
{
    // NOTE: If you change the class name "Service1" here, 
    // you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        } 
 
        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}

Hosting WCF Service

  • Self Host
  • IIS hosting
  • Windows service
  • WAS

Demo of Self hosting and IIS hosting.

Self Hosting

Step 1

Create new project >> Class Library >> name this project as Host.

Image 4

Step 2

Add reference to the host application. Right click on Reference >> Add Reference.

Image 5

Step 3

After adding reference to the host application to expose webservice for client to consume as you see below line of the code creates the object of the host and which is of type Service1 which we created in the WCF Service library project:

C#
using (System.ServiceModel.ServiceHost host = 
	new System.ServiceModel.ServiceHost(typeof(Service1)))
            {
            }

As you can see, we used using block over so that it disposes host object when we close application.

Step 4

To start the service to handle request coming from the client of their service, you need to call open method:

C#
host.Open();

and to stop receiving request, you need to call close method.

Host.cs
C#
namespace HostApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (System.ServiceModel.ServiceHost host = 
		new System.ServiceModel.ServiceHost(typeof(Service1)))
            {
                host.Open();

                Console.WriteLine("Service started. press any key to stop it");
                Console.ReadLine();

                host.Close();
            }
        }
    }
}
IIS Hosting
  1. To host same WCF library in your application, create WCF Web application project using WCF web application template as we discuss in start.
  2. Delete the files created in the IService.cs and Service.cs file from App_Code folder
  3. Include WCF library *.dll file which we created.
  4. Open Service.svc file and modify the single line in it.
    XML
    <xmlns="http://www.w3.org/1999/xhtml"><xmlns="http://www.w3.org/1999/xhtml">
    <%@ ServiceHost Language="C#" Debug="true" 
    Service="WcfServiceLibrary.Service1" %>

Change the web service WEB.Config file to expose service to client, i.e., you need to create same element as listed above in the app.config file of service library.

Consuming WCF Service

Step 1

Create new project >> Class Library >> name this project as Client as we created Host application. If you want to consume webservice hosted in your web application, start directly for the 2 step listed below.

Step 2

Add Service Reference to the client by Right clicking on project >> Add Service Reference.

Image 6

which automatically creates the proxy files to consume web service, or make use of ServiceModel Metadata Utility Tool (Svcutil.exe), the command-line tool to generate proxy code from metadata.

svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config   

Step 3

To send request to service from the client:

C#
ServiceReference1.Service1Client client =  new Client.ServiceReference1.Service1Client();
Console.WriteLine(client.GetData(5));
Console.ReadLine();
client.Close();

So, as you see in the above code, you need to create object of Service1Client and then you can easily call the method exposed by the Service. If you want to see the auto-generated code, press F12 on the Service1Client which shows the proxy code to you.

Summary

As you follow the process listed step by step, it's quite easy to create, consume and host WCF Service.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
QuestionReply Pin
Member 1052720430-Jul-15 1:56
Member 1052720430-Jul-15 1:56 
GeneralMy vote of 2 Pin
Member 923892320-Nov-14 21:02
Member 923892320-Nov-14 21:02 
SuggestionNot clear for complete starters like me. Pin
gopalakrishnach1-May-14 10:55
gopalakrishnach1-May-14 10:55 
QuestionThanks . very Simple and Quick point to point Pin
ashu_om11-Mar-14 9:39
ashu_om11-Mar-14 9:39 
QuestionIt's confusing the BaseAddress and the Endpoint Address - Pin
Dac10-Oct-13 11:28
Dac10-Oct-13 11:28 
GeneralMy vote of 5 Pin
Sandesh M Patil16-Jul-13 6:14
Sandesh M Patil16-Jul-13 6:14 
GeneralEasiest way to create and consume WCF Services in asp.net Pin
Lalit24rocks14-May-13 21:42
Lalit24rocks14-May-13 21:42 
SuggestionNot Explained Properly Pin
Suprabhat Dutta25-Sep-12 6:34
Suprabhat Dutta25-Sep-12 6:34 
QuestionWCF Project Pin
chirag7mca22-Sep-12 0:48
chirag7mca22-Sep-12 0:48 
QuestionNot explain properly.. Pin
my_sanjeev18-Sep-12 0:49
my_sanjeev18-Sep-12 0:49 
GeneralMy vote of 1 Pin
sonu singh chauhan5-Sep-12 21:22
sonu singh chauhan5-Sep-12 21:22 
GeneralMy vote of 5 Pin
Christian Amado24-Aug-12 5:44
professionalChristian Amado24-Aug-12 5:44 
GeneralMy vote of 5 Pin
sravani.v21-May-12 23:34
sravani.v21-May-12 23:34 
QuestionConsume WCF service in Windows Service Pin
pankaj8813-May-12 18:40
pankaj8813-May-12 18:40 
GeneralMy vote of 5 Pin
Wilder Bellamy11-Apr-12 8:06
Wilder Bellamy11-Apr-12 8:06 
QuestionWCF Service Application comes up under Visual C# but not VisualC#/Web on my box Pin
Wilder Bellamy10-Apr-12 9:40
Wilder Bellamy10-Apr-12 9:40 
AnswerRe: WCF Service Application comes up under Visual C# but not VisualC#/Web on my box Pin
Wilder Bellamy11-Apr-12 4:44
Wilder Bellamy11-Apr-12 4:44 
QuestionNeed Help Pin
vikram_sablok28-Mar-12 3:27
vikram_sablok28-Mar-12 3:27 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey27-Mar-12 4:03
professionalManoj Kumar Choubey27-Mar-12 4:03 
GeneralMy vote of 5 Pin
Aditya Vikram Jaiswal3-Feb-11 20:16
Aditya Vikram Jaiswal3-Feb-11 20:16 
GeneralMy vote of 5 Pin
Michael_Nattfalk27-Jan-11 22:51
Michael_Nattfalk27-Jan-11 22:51 
GeneralRe: My vote of 5 Pin
Pranay Rana27-Jan-11 22:53
professionalPranay Rana27-Jan-11 22:53 
GeneralMy vote of 5 Pin
kdgupta8725-Jan-11 0:29
kdgupta8725-Jan-11 0:29 
GeneralRe: My vote of 5 Pin
Pranay Rana25-Jan-11 0:33
professionalPranay Rana25-Jan-11 0:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.