Create and consume WCF service after hosting it in IIS

This article will guide you through, to create a WCF service, host it in your local IIS and consume the service using a client console application. The data are going to be retrieved from an SQL Server 2012 using the Entity Framework. The database used in this tutorial is the AdventureWorks, a sample database which Microsoft provides for free. You can download it but have in mind that you need to convert it to a database compatible to the SQL Server 2012. If you have earlier versions like SQL Server 2008 R2 I am pretty sure you won’t have any problem. Before starting, I assume you have already installed the above database in your SQL Server. So let’s start:

1. Open VS 2012 and create a new class library project (C# template). Name your solution AdventureWorksService and the project name AdventureWorksEntityModel. This class library will provide as the database access through the Entity Framework. Delete Class1.cs file and right click the project to add a new Item of type ADO.NET Entity Data Model. Name it AdventureWorksModel. In the wizard appears next, click “create from database”. Create a new connection to the AdventureWorks database to your server. You should peek Microsoft SQL Server as a datasource, fill your server name and select the database from the dropdown list. Test your connection to assure everything is ok.


Click OK, and continue till you select the tables for your Entity Framework. These will be your Entities. Select from Production, the Product and ProductCostHistory tables. Leave all the rest at the default values.


Click finish, save the edmx file and build the solution. The Entity Model is ready. At the next step we are going to create the service through a WCF website. We ‘ll use this website to publish it in the IIS so we can later consume the service from there.

2. Right click the solution (be careful, not the class library project) and add a new website. From templates select WCF servise. As a location browse to the folder of your solution and add a \AdventureWorksService\ so it will be created under a new folder with the same name as the solution. Rename the file IService.cs file to IAdventureWorksService.cs. This will be the service interface where the contracts will be declared. Remove all the code from it, except the using declarations. Add the following code to the file.

namespace AdventureWorks
// Data contract describing the details of a product passed to client applications
public class ProductData
public string Name;
public string ProductNumber;
public string Color;
public decimal ListPrice;

// Service contract describing the operations provided by the WCF service
public interface IAdventureWorksService
// Get the product number of every product
List<string> ListProducts();
// Get the details of a single product
ProductData GetProduct(string productNumber);

At the next step we ‘ll implement the interface. First of all, we need to add two basic references to our website project. Right click it, select add reference and add the System.Data.Entity assembly and the AdventureWorksEntityModel project. Rename the Service.cs file to AdventureWorksService.cs, delete the entire code from it except the using declarations. Add the above code to the file. Be careful with the “using AdventureWorks2012Entities” code. Your App.config file in your Entity Model project may have save the connection string with different name. Also, copy the the entire connection string element (from start to end) and paste it to the Web.config file of your website project right after the opening configuration tag.

using AdventureWorksEntityModel;

namespace AdventureWorks
public class AdventureWorksServiceImpl : IAdventureWorksService
public List<string> ListProducts()
// Create a list for holding product numbers
List<string> productsList = new List<string>();
// Connect to the AdventureWorks database by using the Entity Framework
using (AdventureWorks2012Entities database = new AdventureWorks2012Entities())
// Fetch the product number of every product in the database
var products = from product in database.Products
select product.ProductNumber;
productsList = products.ToList();
// Ignore exceptions in this implementation
// Return the list of product numbers
return productsList;

public ProductData GetProduct(string productNumber)
// Create a reference to a ProductData object
// This object will be instantiated if a matching product is found
ProductData productData = null;
// Connect to the AdventureWorks database by using the Entity Framework
using (AdventureWorks2012Entities database = new AdventureWorks2012Entities())
// Find the first product that matches the specified product number
Product matchingProduct = database.Products.First(
p => String.Compare(p.ProductNumber, productNumber) == 0);
productData = new ProductData()
Name = matchingProduct.Name,
ProductNumber = matchingProduct.ProductNumber,
Color = matchingProduct.Color,
ListPrice = matchingProduct.ListPrice
// Ignore exceptions in this implementation
// Return the product
return productData;

Change the content of the Service.svc file located at the root of the website to the following

<%@ ServiceHost Language="C#" Debug="true" Service="AdventureWorks.AdventureWorksServiceImpl" CodeBehind="~/App_Code/AdventureWorksService.cs" %>

At this time already, if you right click the service.svc file and select view in browser you should already see that the service is hosted. But not in your local IIS. At the moment it is hosted either in the IIS Exrpress or the ASP.NET Development Server.


Before we create the Client Application to consume the web service, let’s host it first, to the IIS. To do this, simply right click your web project, select publish web site, select Local IIS from left, click on the Default Web Site and for target location put


. That’s it! Go with your browser to the following URL


and you should see the same image as above. If not, be sure the the application pool that the hosted website use in your IIS is ASP.NET 4.0.

3. Right click the solution and create a C# Console Application project named AdventureWorksClient. Add a reference to the System.ServiceModel assembly. Next right click again the console application project, select add a service reference. As address put the service address in your IIS, that would be


(depending of how you named your website). This will retrieve the metadata of the service and will create the proxy for the client, in order to consume the service. Name the namespace AdventureWorksService and click OK. Before I show you the code for calling the service, go to the App.config file of the console application project and ensure that the endpoint address points to the IIS hosted service. Your App.config should be kind like this:

<?xml version="1.0" encoding="utf-8" ?>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
<binding name="BasicHttpBinding_AdventureWorksService" />
<endpoint address="http://localhost/AdventureWorksService/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_AdventureWorksService"
contract="AdventureWorksService.AdventureWorksService" name="BasicHttpBinding_AdventureWorksService" />

Remove all the code from the Program.cs file except the using declarations. Add the following code, right click the Client project and select Set as Start up project. Then run without debugging and you should see the client consuming the service, showing the results for the requested product.

using AdventureWorksClient.AdventureWorksService;

namespace AdventureWorksClient
class Program
static void Main(string[] args)
// Create a proxy object and connect to the service
AdventureWorksService.AdventureWorksServiceClient proxy = new AdventureWorksService.AdventureWorksServiceClient();

// Obtain a list of all products
Console.WriteLine("Test 1: List all products");
string[] productNumbers = proxy.ListProducts();
foreach (string productNumber in productNumbers)
Console.WriteLine("Number: {0}", productNumber);

Console.WriteLine("Test 2: Display the details of a product");
ProductData product = proxy.GetProduct("AR-5381");
Console.WriteLine("Number: {0}", product.ProductNumber);
Console.WriteLine("Name: {0}", product.Name);
Console.WriteLine("Color: {0}", product.Color);
Console.WriteLine("Price: {0}", product.ListPrice);

// Disconnect from the service
Console.WriteLine("Press ENTER to finish");


I hope I helped!


Categories: WCF


7 replies

  1. Howdy! Would you mind if I share your blog with my zynga group?

    There’s a lot of folks that I think would really enjoy your content.
    Please let me know. Cheers

  2. Awesome site you have here but I was curious about if you knew of
    any user discussion forums that cover the same topics discussed here?
    I’d really love to be a part of online community where I can get feed-back from other knowledgeable individuals that
    share the same interest. If you have any recommendations,
    please let me know. Many thanks!

  3. Thanks for posting this . iwas helped me to come out lot of problems ..
    thanks lot..

  4. Hi Chris. Could you help? When I host my WCF service on WcfSvcHost in VS my WCF service can read data from SQL db. In case when I host service on Console App or IIS I have exception fault. Do you know where the probmem could be? Many thanks.

  5. Hi.

    That’s a great Post. Can you help me? I want to update the data. But I have no idea how.


  1. Host and consume a WCF service over TCP | chsakell's Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


about the city and the people

Automating infrastructure one line at a time

Diary Of A Programmer

Because every day is worth noting

chsakell's Blog



A Front End Developer's Blog

Muhammad Hassan

Full Stack Developer | ASP.NET | MVC | WebAPI | Advanced Javascript | AngularJS | Angular2 | C# | ES6 | SQL | TypeScript | HTML5 | NodeJS, MS candidate @LUMS, Grad & EX-Adjunct Faculty @NUCES-FAST, seasonal blogger & open-source contributor. Seattle, WA.

Software Engineering

Web development


.NET, ASP.NET, C#, MVC, TypeScript, AngularJS

Dominick Baier on Identity & Access Control

Happy DotNetting

In Love with Technology

Knoldus Blogs

Insights and Perspectives to keep you updated


Search - Read - Request - Share

Rahul's space

Learn, Share and Grow with me !

Dhananjay Kumar

Developer Evangelist @Infragistics | MVP @Microsoft | Organizer ng-India, India Angular Conference

SQL Authority with Pinal Dave

SQL Server Performance Tuning Expert

Conficient Blog

Random bits of tech from @conficient

Code! Code! Code!


Code Wala

Designing and coding

Microsoft Mentalist

A way to start with Microsoft Technologies

%d bloggers like this: