How to create and consume WCF Services in asp.net ?

Introduction: Windows Communication Foundation (WCF) previously known as "Indigo" is a framework for building configuring and deploying network distributed system .Wcf is a service-oriented application. Using WCF we can build connected secure, reliable, transacted solutions that integrate across platforms.

Description: In some of my previous articles i demonstrated with example  How to create WCF Service to bind,insert,edit,update,delete from sql server database in asp.net  and  How to create crystal reports in visual studio 2010 using asp.net and How to Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net C#

Now in this article i will explain with example how easily you can create your first WCF service and how to consume WCF service. It is a network distributed system developed by Microsoft for communication between applications interoperate between WCF-based applications and any other processes that communicate via SOAP (Simple Object Access Protocol) messages.

WCF allows sending data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages that can be sent can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

WCF Hosting
Web services that was used earlier was hosted inside web server such as IIS using http or wsHttp protocols. But WCF (Windows Communication Foundation) supports four types of hosting.
  •  IIS 
  •  WAS (Windows process activation services) 
  •  Self-hosting 
  •  Windows services

What is ABC in WCF
We had gone through the feature of WCF and understood why its termed as advanced version of web services. Now it’s time to answer a very basic question related to WCF i.e., what is ABC of WCF?

When we say WCF, we came across end points. Service endpoint can be a part of continuously hosted service hosted in IIS or service hosted in an application.
ABC where "A"stands for Address,"B" stands for Binding and "C" stands for Contract are the three elements which constitutes and Service Endpoint.
  • Address - Where the Service is residing (URL of the service.) i..e. where the service is?
  • Binding – Way to talk to the service? Example – basicHttpBinding, wsHttpBinding, webHttpBinding etc. 
  • Contract – What can the service do for me?
Advantages:
  • WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net. 
  • WCF services provide better reliability and security in compared to ASMX web services. 
  • In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Instead it requires small changes in the configuration. 
  • WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
Let's create WCF application and its consuming application:

  • Open visual studio ->File -> New ->Website -> select Visual C# language from the left pane and WCF Service from the right pane and Name it WcfSample or whatever you want. 
  • Now it will create a file Service.svc and two files IService.cs and Service.cs under App_Code folder in Solution Explorer 
  • In the IService.cs interface remove all existing sample code that is placed in the interface IService and let’s declare our own functions as:
[ServiceContract]
public interface IService
{
    [OperationContract]
    int GetEmpId(int id);
    [OperationContract]
    string GetEmpName(string name);
    [OperationContract]
    string GetDept(string dept);
    [OperationContract]
    int GetBasicSalary(int BasicSal);
    [OperationContract]
    int GetPF(int BasicSal);
    [OperationContract]
    int GetHRA(int BasicSal);
    [OperationContract]
    int GetGrossSalary(int BasicSal);
}
  • Similarly remove all existing sample code that is placed inside the Service class in the Service.cs file and write define the function. Our Service.cs file will look like as:
public class Service : IService
{   
    public int GetEmpId(int id)
    {
        return id;
    }

    public string GetEmpName(string name)
    {
        return name;
    }

    public string GetDept(string dept)
    {
        return dept;
    }

    public int GetBasicSalary(int BasicSal)
    {
        return BasicSal;
    }

    public int GetPF(int BasicSal)
    {
        return (BasicSal * 7) / 100;
    }

    public int GetHRA(int BasicSal)
    {
        return (BasicSal * 4) / 100;
    }

    public int GetGrossSalary(int BasicSal)
    {
        return BasicSal + GetPF(BasicSal) + GetHRA(BasicSal);
    }
}
  • Now in web.config file write as:  
<system.serviceModel>
                                <services>
                                                <service name="Service" behaviorConfiguration="ServiceBehavior">
                                                                <endpoint address="" binding="wsHttpBinding" contract="IService">
                                                                                <identity>
                                                                                                <dns value="localhost"/>
                                                                                </identity>
                                                                </endpoint>
                                                                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
                                                                </endpoint>
                                                </service>
                                </services>
                                <behaviors>
                                                <serviceBehaviors>
                                                                <behavior name="ServiceBehavior">
                                                                                <!-- 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>
                                <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
                </system.serviceModel>

  • Congratulations you have created a Wcf service. Now make Service.svc file as startup page by right clicking on the Service.svc file in the solution explorer and select “set as start up page” and run the website. If everything is fine then it will look like as shown in the image below:

WCF example in asp.net
Click on image to enlarge

  • Copy the URL of the service. Here in our example it is “http://localhost:1416/WcfSample/Service.svc”
Note: Leave the Wcf application  running.

Consuming WCF Service

Now it’s time to create a consuming application that will consume the service provided by WcfSample service we just created.

Create a new website as:
Open visual studio ->File -> New ->Website -> select Visual C# language from the left pane and ASP.NET Empty website from the right pane and Name it "ConsumingWcfSample" or whatever you want.
Add a new page as: Website menu-> Add new item ->Web Form-> default.aspx

Now add the service reference of the WCF service we created as:
Right click on the ConsumingWcfSample website and select Add Service Reference and paste the WCF service address (“http://localhost:1416/WcfSample/Service.svc”) that we copied earlier in the address box. Notices that ServiceReference is the namespace that is to be included on the page where we want to consume the WCF service .You can also rename it as per your choice. But we have not changed the default name. Click on GO button

WCF example in asp.net
Click on image to enlarge


You can also view all the functions declared in the IService by clicking on the Service-> IService in the  Add Service Reference box as shown in image below:

WCF example in asp.net
Click on image to enlarge
  • Now In the design page default.aspx create the structure as:
<table>
        <tr>
                <td>
                    Employee ID</td>
                <td>
                    <asp:TextBox ID="txtEmpID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Employee Name</td>
                <td>
                    <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Department</td>
                <td>
                    <asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Basic Salary</td>
                <td>
                    <asp:TextBox ID="txtBasicSal" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                        onclick="btnSubmit_Click"/>
                </td>
            </tr>
        </table>
  • In the code behind file default.aspx.cs
Add the following required namespace:

Using ServiceReference;
  • In the submit button click event write the code as:
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
        Response.Write("Employee ID: " + obj.GetEmpId(Convert.ToInt32(txtEmpID.Text.Trim())));
        Response.Write("<BR/>Employee Name: " + obj.GetEmpName(txtEmpName.Text.Trim()));
        Response.Write("<BR/>Employee Department: " + obj.GetDept(txtDept.Text.Trim()));
        Response.Write("<BR/>Basic Salary: " + obj.GetBasicSalary(Convert.ToInt32(txtBasicSal.Text.Trim())));
        Response.Write("<BR/>PF: " + obj.GetPF(Convert.ToInt32(txtBasicSal.Text.Trim())));
        Response.Write("<BR/>HRA: " + obj.GetHRA(Convert.ToInt32(txtBasicSal.Text.Trim())));
        Response.Write("<BR/>Gross Salary: " + obj.GetGrossSalary(Convert.ToInt32(txtBasicSal.Text.Trim())));
    }

  • Now run the default page and enter the details as:
WCF example in asp.net
Click on image to enlarge
  • And click on submit. It will call the WCF service methods and process the data and return the Output as :
WCF example in asp.net
Click on image to enlarge


Now suppose you want to add another function or make modification in the existing functions then how it is possible?
In fact it’s very easy. What you need to do is to add another function or modify existing function in the WCF service and then run the service.
Now open your ConsumingWcfSample application and right click on the App_WebReferences folder under solution explorer and click on Update Web/Service References as:

WCF example in asp.net
Click on image to enlarge
Now over to you: 
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates." 
Previous
Next Post »

49 comments

Click here for comments
Anonymous
admin
May 03, 2013 ×

very informative article...it cleared all my doubts... perfect!!
: )

Reply
avatar
May 03, 2013 ×

thanks for your valuable feedback..keep reading and get updated always.

Reply
avatar
kishore
admin
May 23, 2013 ×

Thank U BOSS it's very use full for me

Reply
avatar
June 05, 2013 ×

really great article thank you so much...

Reply
avatar
June 05, 2013 ×

very clear and usefull post on WCF great thanx...

Reply
avatar
June 06, 2013 ×

thanks for your valuable feedback bhagwat..keep reading for similar useful articles

Reply
avatar
Anonymous
admin
July 11, 2013 ×

Good article for beginners - Ramesh Venkat

Reply
avatar
July 11, 2013 ×

Thanks for your feedback Ramesh Venkat. Yes this article was solely written form the beginners. I will post the articles on WCF for intermediate level and experts very soon. Stay tuned for more updates

Reply
avatar
Aysa
admin
July 17, 2013 ×

Thank u so much lalit...i m new follower of ur blog...vry useful content..till date i have so many doubt about WCF and nw it cleared..again thanks a lot.

Reply
avatar
July 17, 2013 ×

thanks for your appreciation..Stay tuned for more updates

Reply
avatar
Gurmeet
admin
July 23, 2013 ×

Boss Done great Job
Keep it up
And how to use session in my application and after some times it tell me session expires
are u continue yes or no

Reply
avatar
July 23, 2013 ×

Thanks gurmeet and read the article to solve your session expire problem
How to increase session timeout period in asp.net
http://www.webcodeexpert.com/2013/02/how-to-increase-session-timeout-period.html

Reply
avatar
Anonymous
admin
August 02, 2013 ×

This is awesome!! really helpful for me. Thanks for sharing with us. It helped me to complete my task.

Reply
avatar
Unknown
admin
August 12, 2013 ×

very nice article for wcf begineers,..
Can you please post some more article,examples,code snippets on WCF..

Reply
avatar
Unknown
admin
August 12, 2013 ×

very nice article for wcf begineers,..
Can you please post some more article,examples,code snippets on WCF..

Reply
avatar
Unknown
admin
August 12, 2013 ×

Sir..Can you please provide code Snippets where Interface Concept,Data Abstraction,Sealed class,Abstract class is implemented..I would be very thankfull...

Reply
avatar
August 12, 2013 ×

Thanks for the feedback Asif..Please check my another article on WCF..hope it will be more useful for you
WCF Service to bind,insert,edit,update,delete from sql server database in asp.net C#
http://www.webcodeexpert.com/2013/08/wcf-service-to-bindinserteditupdatedele.html

Reply
avatar
August 12, 2013 ×

hello Asif..thanks for the reading and suggestions..I'll post related to Interface Concept,Data Abstraction,Sealed class,Abstract classes in my upcoming articles..please stay tuned for updates..

Reply
avatar
Unknown
admin
August 21, 2013 ×

Sir , u r d best .... all the articles are best with simplest code snippet and examples ... i m beginner in advance will u plz further cover some advance topics of wcf and wpf.

Thanks

Reply
avatar
August 21, 2013 ×

Thanks for the appreciation..this blog has article for the beginners as well as experienced..and it is growing so stay tuned for the more advanced topics as per your suggestions..

Reply
avatar
Anonymous
admin
August 29, 2013 ×

nice article.....really good stuff for beginners.....

Reply
avatar
August 29, 2013 ×

thanks for the appreciation..

Reply
avatar
Unknown
admin
September 09, 2013 ×

thanku u sir very useful article for me and all wcf beginners....

Reply
avatar
September 09, 2013 ×

thanks for appreciating this article..keep reading..

Reply
avatar
Anonymous
admin
September 19, 2013 ×

Thank You! It was "Very" Imformative!

Reply
avatar
September 19, 2013 ×

Thanks for your appreciation..keep reading..

Reply
avatar
Anonymous
admin
September 22, 2013 ×

I have followed the instructions but i get error saying "metadata publishing for this service is currently disabled" i have double and triple cheked the code with no error. can you tell me what might be wrong on my end. please.

Reply
avatar
September 23, 2013 ×

Hi, it seems there is any error in setting service name,behavior etc your web.config. i suggest you to recheck that and notify me..if still you face error then send your sample project to me on my email lalit24rocks.com and i will check and help you to sort out the problem..

Reply
avatar
Unknown
admin
October 14, 2013 ×

finally got what i want to start wcf . thank you so much sir

Reply
avatar
October 14, 2013 ×

Your welcome Ajay..stay connected and keep reading for more useful updates like this..:)

Reply
avatar
November 25, 2013 ×

Thanks Lalit for a nice article for beginners of WCF.

Im so much confuse to where i start to learn wcf.

Now im cleared about wcf. Can u give me one more example which service have work with sql database and produce some complex results in form of text based on some client input and produce result to client machine. and tell me how to security and other things are managed in that example

Reply
avatar
November 25, 2013 ×

Hi, also read the article to learn more about WCF
WCF Service to bind,insert,edit,update,delete from sql server database in asp.net C#
http://www.webcodeexpert.com/2013/08/wcf-service-to-bindinserteditupdatedele.html

Reply
avatar
Anonymous
admin
February 16, 2014 ×

very nice article

Reply
avatar
February 17, 2014 ×

I am glad you found this article useful..stay connected and keep reading..:)

Reply
avatar
Unknown
admin
March 11, 2014 ×

Great Work Useful Article....

Reply
avatar
March 14, 2014 ×

Hello lohith r..thanks for appreciating my work..i am glad you found this article helpful..stay connected and keep reading..:)

Reply
avatar
Unknown
admin
March 19, 2014 ×

Thank You!
Nice Article!

Reply
avatar
March 19, 2014 ×

Hello tilahun abebe..thanks for appreciating my work..it is always nice to hear that someone found my articles helpful..stay connected and keep reading for more useful updates..:)

Reply
avatar
Rasmita
admin
March 28, 2014 ×

Good job!
It is very helpful...
Got my basics cleared here

Thanks :)

Reply
avatar
March 28, 2014 ×

Hi Rasmita..i am glad you found this article helpful..stay connected and keep reading...:)

Reply
avatar
Parth Patel
admin
April 07, 2014 ×

Very Nice and Clear Work Lalit Sir...
This is my 1st Programm of Wcf & It's Work Properly...
But I am Still confused for What the Change done in Web.config File...
And Why we need to change it???

Reply
avatar
Parth Patel
admin
April 07, 2014 ×

It's very Nice and Clear Work Lalit Sir...
this is my 1st Programm in WCF and it's Work Successfully
But, I am Still Confused for what Change done in Web.config and why????

Reply
avatar
Anonymous
admin
April 08, 2014 ×

hey lalit its very useful for me really
let me know ur cell number in case i need more help

Reply
avatar
April 10, 2014 ×

Thanks for appreciating my work..it is always nice to hear that my article helped anyone in learning asp.net..in case you need my help you can comment here...stay connected and keep reading..:)

Reply
avatar
Java
admin
June 10, 2014 ×

hi.how to select data in asp.net using web revice in xml format? :( please help me.

Reply
avatar
Anonymous
admin
May 28, 2016 ×

Finally! a page that explains in simple and easy steps by steps the use of WCF.

Reply
avatar
Unknown
admin
June 02, 2016 ×

Thanks a lot for help..

Reply
avatar
June 02, 2016 ×

Thanks for your feedback..Stay connected and keep reading for more useful updates

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..