6 out of 36 rated this helpful - Rate this topic

How to: Host a WCF Service in IIS

This topic outlines the basic steps required to create a Windows Communication Foundation (WCF) service that is hosted in Internet Information Services (IIS). This topic assumes you are familiar with IIS and understand how to use the IIS management tool to create and manage IIS applications. For more information about IIS see Internet Information Services A WCF service that runs in the IIS environment takes full advantage of IIS features, such as process recycling, idle shutdown, process health monitoring, and message-based activation. This hosting option requires that IIS be properly configured, but it does not require that any hosting code be written as part of the application. You can use IIS hosting only with an HTTP transport.

For more information about how WCF and ASP.NET interact, see WCF Services and ASP.NET. For more information about configuring security, see Windows Communication Foundation Security.

For the source copy of this example, see IIS Hosting Using Inline Code.

To create a service hosted by IIS

  1. Confirm that IIS is installed and running on your computer. For more information about installing and configuring IIS see Installing and Configuring IIS 7.0

  2. Create a new folder for your application files called "IISHostedCalcService", ensure that ASP.NET has access to the contents of the folder, and use the IIS management tool to create a new IIS application that is physically located in this application directory. When creating an alias for the application directory use "IISHostedCalc".

  3. Create a new file named "service.svc" in the application directory. Edit this file by adding the following @ServiceHost element.

    <%@ServiceHost language=c# Debug="true" Service="Microsoft.ServiceModel.Samples.CalculatorService"%>
    
  4. Create an App_Code subdirectory within the application directory.

  5. Create a code file named Service.cs in the App_Code subdirectory.

  6. Add the following using statements to the top of the Service.cs file.

    using System;
    using System.ServiceModel;
    
  7. Add the following namespace declaration after the using statements.

    namespace Microsoft.ServiceModel.Samples
    {
    }
    
  8. Define the service contract inside the namespace declaration as shown in the following code.

    [ServiceContract]
    public interface ICalculator
    {
       [OperationContract]
       double Add(double n1, double n2);
       [OperationContract]
       double Subtract(double n1, double n2);
       [OperationContract]
       double Multiply(double n1, double n2);
       [OperationContract]
       double Divide(double n1, double n2);
    }
    
    
    
  9. Implement the service contract after the service contract definition as shown in the following code.

    public class CalculatorService : ICalculator
    {
       public double Add(double n1, double n2)
       {
          return n1 + n2;
       }
       public double Subtract(double n1, double n2)
       {
          return n1 - n2;
       }
       public double Multiply(double n1, double n2)
       {
          return n1 * n2;
       }
       public double Divide(double n1, double n2)
       {
          return n1 / n2;
       }
    } 
    
    
    
  10. Create a file named "Web.config" in the application directory and add the following configuration code into the file. At runtime, the WCF infrastructure uses the information to construct an endpoint that client applications can communicate with.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
        <services>
          <!-- This section is optional with the default configuration
            model introduced in .NET Framework 4 -->
          <service name="Microsoft.ServiceModel.Samples.CalculatorService">
    
            <!-- This endpoint is exposed at the base address provided by host:                                        http://localhost/servicemodelsamples/service.svc  -->
            <endpoint address=""
                      binding="wsHttpBinding"
                      contract="Microsoft.ServiceModel.Samples.ICalculator" />
    
            <!-- The mex endpoint is exposed at http://localhost/servicemodelsamples/service.svc/mex -->
            <endpoint address="mex"
                      binding="mexHttpBinding"
                      contract="IMetadataExchange" />
          </service>
        </services>
      </system.serviceModel>
    
    </configuration>
    
    

    This example explicitly specifies endpoints in the configuration file. If you do not add any endpoints to the service, the runtime adds default endpoints for you. For more information about default endpoints, bindings, and behaviors see Simplified Configuration and Simplified Configuration for WCF Services.

  11. To make sure the service is hosted correctly, open an instance of Internet Explorer and browse to the service's URL: http://localhost/IISHostedCalc/Service.svc

Example

The following is a complete listing of the code for the IIS hosted calculator service.

using System;
using System.ServiceModel;

namespace Microsoft.ServiceModel.Samples
{

  [ServiceContract]
  public interface ICalculator
  {
     [OperationContract]
     double Add(double n1, double n2);
     [OperationContract]
     double Subtract(double n1, double n2);
     [OperationContract]
     double Multiply(double n1, double n2);
     [OperationContract]
     double Divide(double n1, double n2);
  }


  public class CalculatorService : ICalculator
  {
     public double Add(double n1, double n2)
     {
        return n1 + n2;
     }
     public double Subtract(double n1, double n2)
     {
        return n1 - n2;
     }
     public double Multiply(double n1, double n2)
     {
        return n1 * n2;
     }
     public double Divide(double n1, double n2)
     {
        return n1 / n2;
     }
  } 



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="Microsoft.ServiceModel.Samples.CalculatorService">

        <!-- This endpoint is exposed at the base address provided by host:                                        http://localhost/servicemodelsamples/service.svc  -->
        <endpoint address=""
                  binding="wsHttpBinding"
                  contract="Microsoft.ServiceModel.Samples.ICalculator" />

        <!-- The mex endpoint is explosed at http://localhost/servicemodelsamples/service.svc/mex -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>

</configuration>



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="Microsoft.ServiceModel.Samples.CalculatorService">

        <!-- This endpoint is exposed at the base address provided by host:                                        http://localhost/servicemodelsamples/service.svc  -->
        <endpoint address=""
                  binding="wsHttpBinding"
                  contract="Microsoft.ServiceModel.Samples.ICalculator" />

        <!-- The mex endpoint is explosed at http://localhost/servicemodelsamples/service.svc/mex -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>

</configuration>


See Also

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Instruction for WCF Web Service hosted in IIS
Like many people, I wasn't able to follow instructions provided on this page. MS should test their documentation before publishing world wide and putting their name on it. Anyways, found much clearer steps at

Cheers
Created IIS service
Successfully created service !, followed  Gregor Suttie web configuration $0$0 $0 behavior setting
IIS 7.0+ *can* actually host non-HTTP transport services
The introduction to this article is slightly confusing in that IIS 7.0 and 7.5 can in fact host WCF services with transports other than HTTP. This is done via Windows Process Activation Service(WAS), which MSDN presents as a separate method but is in fact just a new feature of IIS. See the separate article on WAS for info.
KaJun's fix worked for me.
I skipped Kajun's step 1 and step 2 and applied just his step 3a and step 3b. Thank you KaJun!
The xaml in the example is invalid
Use this instead:-

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<!-- This section is optional with the default configuration
model introduced in .NET Framework 4 -->
<service name="Microsoft.ServiceModel.Samples.CalculatorService" behaviorConfiguration="MyServiceTypeBehaviors">
<!-- This endpoint is exposed at the base address provided by host: http://localhost/servicemodelsamples/service.svc -->
<endpoint address=""
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
<!-- The mex endpoint is exposed at http://localhost/servicemodelsamples/service.svc/mex --><!--
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />-->
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors" >
<!-- Add the following element to your service behavior configuration. -->
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>

</system.serviceModel>
</configuration>
.
I could not get this to work
I started again failed, implemented changes provided by generous posters here and again failed.

thanks for wasting my time Microsoft.  Perhaps you can fix the documentation and then improve the tutorials on this?
Gregor's Web.config works
With the article's Web.config I was getting a web page with an error message referring to IMetadataExchange when I accessed the service URL from a browser (http://localhost/IISHostedCalc/Service.svc). 

The contract name 'IMetadataExchange' could not be found in the list of contracts implemented by the service CalculatorService.

After changing the Web.config to Gregor's settings and restarting the webapp now I see a page saying "You have created a service." when accessing the service URL from a browser.  Yay!

I am running IIS 7.5 and .NET 4.0 application pools.

Placement of files is wrong
Note that it says to place the *.svc file in the App_Code directory, but there is nothing about placing
the files for the contract defining interface and the class which implements it in the App_Code directory.
This contradicts how the files are assembled in a WCF project in Visual Web Developer Express.  There,
it is the class and interface files which are in the App_Code directory and the *.svc file which is in the root
directory.  
Kajun's Fix Works
Kajun - I'm on Windows 7 - I skipped to your step 3, parts a and b and I got to the "You have created a service" screen. Thanks for saving me a lot of time.
Easier to get the missing config data.
Actually... if you add a "WCF Service" item using the "Add New..." dialog (Ctl + Shift + A), it will automatically provide the markup for the behaviors in a .config file.

I don't see why Microsoft should be missing vital info from their documentation, but its not uncommon.
slight additions to get this working

On my Vista/IIS 7 system and project targeting .net framework 2.0, there were a few additional things to set up first:

1. Have the project target .net framework 3.0 (or 3.5).  The System.ServiceModel reference is needed from there.

2. IIS had to have the .svc handler set up - go to C:\windows\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ in a command prompt (running as administrator) and run "ServiceModelReg –i".  Thanks to Guy Burstein for his blog post about this here: http://blogs.microsoft.co.il/blogs/bursteg/archive/2008/12/01/wcf-on-iis7-on-vista-adding-svc-handler.aspx

3 a Add a behaviorConfiguration attribute to the service tag, it should now look like this:

<service name="Microsoft.ServiceModel.Samples.CalculatorService" behaviorConfiguration="ICalculatorBehaviors">

3 b. Modify the web.config file to specify a service behavior:

        <behaviors>
<serviceBehaviors>
<behavior name="ICalculatorBehaviors" >
<!-- Add the following element to your service behavior configuration. -->
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>

This <behaviors> node goes after the </services> closing tag.

After that, I was able to load up a page saying "You have created a service" in IE, which then gave some instructions on how to create a client to consume the service, etc.

Hope this helps someone else.

KaJun

If you are hosting in IIS, you should use Windows Server AppFabric with it
Windows Server AppFabric extends your IIS hosting experience to provide additional management and monitoring

For more information see msdn.microsoft.com/appfabric