Hosting a WCF Service in IIS / C#

Step 1: Create a new Visual Studio project

Choose the WCF installed template and create a new WCF Service Application:

Step 2: Create your web service code

Update the IService1.cs and Service1.svc.cs classes that are automatically created.

You can of course delete these and create your own but I am re-using here for the sake of brevity.

For ease of demonstration I will create an extremely simple “Hello world!” example.

IService1.cs

using System.ServiceModel;
using System.ServiceModel.Web;

namespace WcfService
{  
   [ServiceContract]
   public interface IService1
   {
      [OperationContract]
      [WebGet(UriTemplate = "/HelloWorld/")]
      string HelloWorld();
   }
}

Service1.svc.cs

namespace WcfService
{
   public class Service1 : IService1
   {
      public string HelloWorld()
      {
         return "Hello world!";
      }
   }
}

Re-build the visual studio project.

Observe that a bin/ folder containing our libraries is then created.

When creating the service using IIS manager we will need this as well as the web.config and Service1.svc files.

Step 3: Create the IIS service

Open IIS Manager.

Navigate to the folder location at which you would like to create the the service – right click and select Explore.

Create the folder which will contain your web service code (confidential bits redacted)

Navigate to this folder and copy in the bin/ folder and Service1.svc / web.config files created that were mentioned previously.

Now in IIS manager select Add application.
Fill in the details (some details here redacted for confidentiality)

Click OK.

Here is mine, again with confidential bits scrubbed out:

To quickly test the service, right click on the service and select Manage Application > Browse.

The service should appear in a browser as shown:

Step 4 – consume the web service.

In your Visual Studio, create a new Console Application.

On the solution folder select Add > New Project…

Set this console app as the selected startup application.

In the console set the project dependencies like so:

And also make sure the WCF service project is also being referenced:

Add a service reference.

Right click the console app project and select Add > Service Reference…

Set the URL of your IIS manager service and press the Go button:

(I’ve redacted part of the url also for confidentiality)

Click OK.

Step 5: Consume the service

Modify Program.cs to access the web service reference:

Program.cs

using System;
using WebServiceConsumer.Service;

namespace WebServiceConsumer
{
   internal static class Program
   {
      private static void Main()
      {
         var service = new Service1Client();

         Console.Write(service.HelloWorld());
      }
   }
}

On running the program the web service set up in IIS manager is accessed as shown:

`