WCF Services: Configuration (File and/or programatically)

Description and samples
Table of Contents
Summary

The WCF configuration is required at serviceclient and host level. When not done through code it must be set as described bellow.

Description

The configuration of WCF services is set within the “system.serviceModel” node.

The configuration for each service is set on the the “service nodes:

Node Attr/Chl Element Description Remarks
serviceHostingEnvironment Defines the type the service hosting environment instantiates for a particular transport
aspNetCompatibilityEnabled If set to “True” indicates whether the ASP.NET compatibility mode has been turned on for the current application. The default is false. When this attribute is set to true, requests to WCF services flow through the ASP.NET HTTP pipeline, and communication over non-HTTP protocols is prohibited. For more information, refer to WCF Services and ASP.NET
protocolMapping Mapping definition between transport protocol schemes (e.g., http, net.tcp, net.pipe, etc.) and WCF bindings.
Used when creating default endpoints at runtime.
Defined on the machine.config file.
Specific to WCF 4.0
By default configured as:
<protocolMapping>
<add scheme=”http” binding=”basicHttpBinding”/>
<add scheme=”net.tcp” binding=”netTcpBinding”/>
<add scheme=”net.pipe” binding=”netNamedPipeBinding”/>
<add scheme=”net.msmq” binding=”netMsmqBinding”/>
</protocolMapping>
protocolMapping/add scheme Scheme reference name (http, https, net.tcp, net.pipe, net.msmq)
binding Binding method associated
protocolMapping/remove scheme Scheme reference name (http, https, net.tcp, net.pipe, net.msmq) Overrides and removes a mapping configured by default on the machine.config file
serviceHostingEnvironment/serviceActivations Defines virtual service activation endpoints that map to service types in order to void having to maintain physical .svc files when hosting services on IIS. Specific to WCF 4.0.
serviceHostingEnvironment/serviceActivations/add relativeAddress The relative address within the current IIS application (e.g. “Service1.svc”).
service The Service Type that implements the service (either the full qualified Typename or the short Typename (when it is placed in the App_Code folder).
factory A string that specifies the CLR type name of the factory that generates a service activation element. Optional.
By default is used the base ServiceHostFactory class.
services Configuration required by WCF for each service
service name Identifies the concrete implementation of the service.
Read by the ServiceHost instance to find which section of the configuration file to use
.NET class qualified name.
Optional element on WCF 4.0.
Service(s) without specific configuration will use default endpoints, behaviors and bindings.
behaviorConfiguration Identifies a section of the configuration file that will contain information about what behaviors the service will use.
Used to specify which behavior of the “serviceBehaviors” section the service should use.
Read by the ServiceHost instance to find which section of the configuration file to use (section “serviceBehaviors”)
Its value is matched with the name attribute of the “behavior” element
service/endpoints Specifies the service endpoint(s) which clients use to invoke the service
service/endpoints/endpoint Specifies the ABC of the endpoint: Address, Binding and Contract
address Uri for location of the service that allows clients to locate the service on a network and invoke it’s actions or acquire it’s metadata.
The address is append to the base address and if not required must be set with the empty value
binding Indicates the binding method which specifies how the service communicates with the client In order to alter default definitions the binding type must have one or more registered configuration sections within the main <bindings> section
bindingconfiguration Used to distinguish between bindings of the same type.
Its value is matched with the name attribute of the binding’s registered configuration sections
Refer to the ”References” section of the article  for details
contract Identifies the service contract implemented by the service
behaviorConfiguration Used to specify which behavior of the “endpointBehaviors” section the endpoint should use.
Its value is matched with the name attribute of the “behavior” element
Refer to the “References” section of the article  for details
kind Specifies the name of a pre-configured standard endpoint. Specific to WCF 4.0
endpointConfiguration Used to specify on the “StandardEndpoints” section the configuration options to use for this endpoint type. Specific to WCF 4.0
To be used when pre-configured options of the defined standard endpoint must be adapted for the service.
standardEndpoints Configuration file section associated to standard endpoints Specific to WCF 4.0
The most common used defined standard endpoints are:

Name Description
mexEndpoint Defines a standard endpoint for MEX configured with IMetadataExchange for the service contract, mexHttpBinding as the default binding (customizable), and an empty address.
webHttpEndpoint Defines a standard endpoint configured with the WebHttpBinding and the WebHttpBehavior, Used to expose ReST services.
webScriptEndpoint Defines a standard endpoint configured with the WebHttpBinding and the WebScriptEnablingBehavior. Use to expose Ajax services.
workflowControlEndpoint Defines a standard endpoint for controlling the execution of workflow instances (create, run, suspend, terminate, etc).
standardEndpoints/STANDARDENPOINTNAME/standardEndpoint Configuration file section associated to a specific standard endpoint
name Corresponds to the reference name used on “services/service/kind“.
other attributes Specific attributes according the standard endpoint.
Attribute Description
webHttpEndpoint
automaticFormatSelectionEnabled A Boolean value that indicates whether automatic format selection is enabled.
If enabled, the infrastructure parses the Accept header of the request message and determines the most appropriate response format. If the Accept header does not specify a suitable response format, the Content-Type of the request message or the default response format of the operation.
defaultOutgoingResponseFormat An attribute that specifies the default outgoing response format. This attribute is of the Webmessageformat type.
helpEnabled A Boolean value that indicates whether the HTTP help page is enabled for the endpoint.
webEndpointType A string that specifies the type of the endpoint.
behaviors/serviceBehaviors/behavior Configuration file section associated to the service and that controls certain functionalities and allows to activate certain options
behaviors/serviceBehaviors/behavior name Name that uniquely identifies a service behavior On WCF 4.0 nameless behavior will be used and attached to service’s endpoint(s) where the configuration “behaviorConfiguration” attribute was omitted
behaviors/serviceBehaviors/behavior/serviceMetadata httpgetEnabled If set to “True, specifies if the service should expose the metadata through an HTTP GET request of the WSDL document
behaviors/serviceBehaviors/behavior/serviceDebug includeExceptionDetailsInFault Specifies if the cient should receive exception details for debug purposes
behaviors/serviceBehaviors/behavior/serviceDebug HttpHelpPageEnabled / HttpsHelpPageEnabled / HttpHelpPage* / HttpsHelpPage* Enable and configure the use of a custom HTML help file that is returned from an HTTP GET request to the base address of the service. These properties provide a mechanism to enable a custom help page, however, it will not automatically tell the server to generate a custom page (Refer to sample).
behaviors/endpointBehaviors/behavior Configuration file section associated to the endpoints and that controls certain functionalities and allows to activate certain options
behaviors/endpointBehaviors/behavior name Name that uniquely identifies a endpoint behavior
behaviors/endpointBehaviors/behavior/webHttp helpEnabled Specifies if automatic help pages should be automatically generated for ReST services

 

In case of self-hosting, the configuration of each service of the host application is set on the “host” node:

NODE ATTR/CHL ELEMENT DESCRIPTION REMARKS
service/host/baseAddresses Specify base address(es), which will be pre-pended to the address defined in the service endpoints.
Multiple base addresses can be specified, one per each type of transport
Base address is ignored for IIS/WAS hosts: It is determined by the IIS virtual directory along with the .svc file.
service/host/baseAddresses baseAddress Specify a base address,  for a specific type of transport, which will be pre-pended to the address defined in the service endpoints Format: net.tcp.* / net.msqm.* / http://

 

The configuration of the Client application is set on the “client” node which contains a list of endpoints used  to connect to a service:

Note: The configuration file of a Client application must be named “App.config” since it’s the file name that WCF expects.

NODE ATTR/CHL ELEMENT DESCRIPTION REMARKS
client/endpoint name Name attribute that uniquely identifies an endpoint for a given contract.
Used by the ChannelFactory or by the ClientBase object to specify which endpoint in the client configuration is being targeted and must be loaded when a channel is created to service
Optional
address Specifies the URL that provides the location of the endpoint The address for a service endpoint can also be specified in code by creating a Uniform Resource Identifier (URI) and added to the ServiceHost using one of the AddServiceEndpoint methods
binding Indicates the type of binding the endpoint expects to use when connecting to a service In order to alter default definitions the binding type must have one or more registered configuration sections within the main <bindings> section
bindingconfiguration Used to distinguish between bindings of the same typeIts value is matched with the name attribute of the binding’s registered configuration sections Refer to the ”References” section of the article  for details
contract Specifies which contract the endpoint is exposing. This value maps to the “ConfigurationName” of the .NET “ServiceContract” attribute The default value is the full type name of the class that implements the service

 

The <bindings> section

The main bindings section is used both on client and host side: If any of the default property values must be changed then the a node “bindings/BINDINGNAME” must  be included on the “System.ServiceModel” base section:

e.g.

<system.serviceModel>
  ...
  <bindings>
     <basicHttpBinding>
        <binding name="Binding1"
               receiveTimeout="00:10:00"
               openTimeout="00:10:00"
               transferMode="Buffered"
               messageEncoding="Text"
              <security mode="None" />
         </binding>
     </basicHttpBinding>
  </bindings>
  ...
</system.serviceModel>

These options can also be manipulated in the correspondent properties on the binding classes on System.ServiceModel.

On WCF 4.0 nameless <binding/BINDINGNAME> nodes will be used and attached to service’s endpoint(s) where the configuration “bindingConfiguration” attribute was omitted.

Refer to the  following Microsoft articles for binding descriptions:

[1] Description of the BasicHttpBindig binding
[2] Description of the WebHttpbinding bindng
[3] Description of the WSHttpbinding binding

On WCF 3.x at least one endpoint must be defined per service, otherwise ServiceHost instance will throw an exception;

NET 4.0 offers a Simplified Configuration new feature.
It covers support for default endpoints, binding and behavior configurations.

These changes make it possible to host configuration-free services.

Operations
Service configuration on WCF 3.x

See description here

ReST service configuration on WCF 3.x

See description here

Service configuration with two endpoints, same binding and different binding options (WCF 3.x, WCF 4)
How to do it

In the example below each endpoint uses a different customized “bindingConfiguration” attribute of the same binding type:

<service name="WCF.wcfTestServiceImpl">
    <endpoint
        address="http://computer:8080/TestService1"
        contract="WCF.IwcfTestService"
        binding="basicHttpBinding"
        bindingConfiguration="shortTimeout"
    </endpoint>
    <endpoint
        address="http://computer:8080/TestService2"
        contract="WCF.IwcfTestService"
        binding="basicHttpBinding"
        bindingConfiguration="Secure"
     </endpoint>
</service>
<bindings>
    <basicHttpBinding
        name="shortTimeout"
        timeout="00:00:00:01"
     />
     <basicHttpBinding
        name="Secure" />
        <Security mode="Transport" />
</bindings>

The same behavior can be achived on WCF 4 using the default configuration by adding a <protocolMapping> section and configuring the bindings:

<protocolMapping>
    <add scheme=”http” binding=”basicHttpBinding” bindingConfiguration=”shortTimeout” />
    <add scheme=”https” binding=”basicHttpBinding” bindingConfiguration=”Secure” />
</protocolMapping>
<bindings>
    <basicHttpBinding
        name="shortTimeout"
        timeout="00:00:00:01"
     />
     <basicHttpBinding
        name="Secure" />
        <Security mode="Transport" />
</bindings>
Simplified configuration on WCF 4: Service configuration using default endpoints

When the host application calls ServiceHost::Open on the ServiceHost instance:

1) it builds the internal service description from the application configuration file (if exists);
2) it applies all configuration details (if any) configured explicitly by the host application;
3) if the number of configured endpoints is still zero, it calls ServiceHost::AddDefaultEndpoints method to generate default endpoints to be added to the service descriptionand.

The default endpoints are automatically determined based on:

i) The service’s base addresses (if hosted on IIS this is the “.svc” address; if self-hosted then a base address must be provided at instantiation of the ServiceHost object);
ii) The service contract(s) implemented by the service; and
ii) Selection of the binding configured by the machine or application (if overrided) protocol mapping configuration

in order to add one default endpoint per base address and for each service contract implemented by the service;

e.g. If the service implements two service contracts and the host is configured with two base addresses (one for HTTP and one for TCP), four default endpoints will be added to the service description.

Remarks

This method is public and can be called directly in custom hosting scenarios.

How to do it

 

ServiceHost host = null;

try
 {

	host = new ServiceHost(

			typeof(wcfTestServiceImpl),

			new Uri("http://localhost:35799/training/wcf/app/testservice1"));

	// Configure a custom endpoint...
	host.AddServiceEndpoint(typeof(IwcfTestService), new WSHttpBinding(), "/test");

	// Explicitly add default endpoints...
	host.AddDefaultEndpoints();

	// Initiate host...

	host.Open();

	foreach (ServiceEndpoint se in host.Description.Endpoints)
            Console.WriteLine("A: {0}, B: {1}, C: {2}",
                se.Address, se.Binding.Name, se.Contract.Name);

	Console.WriteLine("Test console host initiated: Press <enter> to close host application");

	Console.ReadLine();

}

catch (Exception ex) 

{

	Console.WriteLine("Test console host could not be initiated or an error occurred during host life cycle: " + ex.ToString());

}

finally

{

	if (host != null)
 {

		if (host.State != CommunicationState.Closed) host.Close();

	}

}
Simplified configuration on WCF 4: Configuration of default behavior options for all services (e.g. expose metadata through WSDL request)

WCF 4 makes it possible to define default behavior configurations for services and endpoints, which can simplify things when defining standard default behavior configuration to be shared across all services or endpoints running on a machine or within a solution.

How to do it

In WCF 3.x, it would be required to define named behavior configurations to be applied explicitly to services and endpoints through the “behaviorConfiguration” attribute:

<configuration>
  <system.serviceModel>
    <services>
      <service name="WCF.wcfTestServiceImpl" behaviorConfiguration="ServiceBehavior">
        <endpoint address ="" binding="basicHttpBinding" contract="WCF.IwcfTestService"/>
      </service>
      <service name="WCF.wcfTestService2Impl" behaviorConfiguration="ServiceBehavior">
        <endpoint address ="" binding="basicHttpBinding" contract="WCF.IwcfTestService2"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

With WCF 4, its possible to define a default behavior configuration by omitting the name in the configuration definition:

<configuration>
  <system.serviceModel>
    <services>
      <service name="WCF.wcfTestServiceImpl">
        <endpoint address ="" binding="basicHttpBinding" contract="WCF.IwcfTestService"/>
      </service>
      <service name="WCF.wcfTestService2Impl">
        <endpoint address ="" binding="basicHttpBinding" contract="WCF.IwcfTestService2"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
Simplified configuration on WCF 4: Configuration of default binding options for all services (e.g. message encoding)

Every WCF binding has built-in default configuration that is used unless explicitly overridden by the host application for a particular endpoint.

Each binding instance always comes with the built-in defaults unless overrided by applying an explicit binding configuration.

Remarks

In order to have this default configuration applied to all services running on the machine, this configuration must be applied on machine.config file, otherwise it will be reflected only in the context of the application.

How to do it

In WCF 3.x, this is achived by defining a named binding configuration to be applied to specific endpoint definitions through the “bindingConfiguration” attribute:

<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="basicHttpBindingWithMtom" messageEncoding="Mtom"/>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="WCF.wcfTestServiceImpl">
        <endpoint address="mtom" binding="basicHttpBinding"
                  bindingConfiguration="basicHttpBindingWithMtom"
                  contract="WCF.IwcfTestService"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

With WCF 4, its possible define default binding configurations by simply omitting the binding configuration name when defining the new configuration. Then WCF will use that default configuration for any endpoints using that binding that don’t have an explicit binding configuration set on them (through the “binding configuration” attribute”):

<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding messageEncoding="Mtom"/>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

 

Simplified configuration on WCF 4: Service configuration using standard endpoints (Description)

WCF 4 makes available a set of common preconfigured endpoint definitions ready to be used.

These “standard” endpoint configuration typically will not change, although it is possible.

WCF 4 provide standard endpoint definitions for some of the most common features and communication scenarios.

These standard endpoints are usabale on any service configuration by referencing them by name on the “kind” attribute of the “endpoint.

The standard endpoints shield from most of the configuration details (e.g., no need to specify the binding or contract).

Remarks

When some parameters need to me adapted the <standardEndpoints> section is used to override the default configuration of the standard endpoint.

Simplified configuration on WCF 4: Service configuration using standard endpoints (e.g. MEX endpoint)
How to do it
<configuration>
  <system.serviceModel>
    <services>
      <service name="WCF.wcfTestServiceImpl">
        <endpoint address="http://localhost:60063/TestService1.svc" binding="wsHttpBinding" contract="WCF.IwcfTestService"
                  behaviorConfiguration="">
        <endpoint kind="mexEndpoint" address="mex" />
      </service>
    </services>
  </system.serviceModel>
</configuration>
Simplified configuration on WCF 4: Service configuration using standard endpoints (e.g. WebHttpBinding with a default webHttpBehavior)

In WCF 4 this configuration element defines a standard endpoint with a fixed <webHttpBinding> binding that automatically adds the &th;webHttp> behavior.

To be used when exposing ReST services.

How to do it

 

<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <behaviors>
      <endpointBehaviors>
        <behavior name="HelpBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="CounterResource">
        <endpoint behaviorConfiguration="HelpBehavior"
                  binding="webHttpBinding"
                  contract="IwcfTestService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

 

Exposing WCF Service metadata information on WCF 3.x

See description here.

Configure virtual service activation: Activate services hosted in IIS without an ".svc" file

Since WCF 4.0, services can be deployed in IIS without a physical “.svc” file.

This can be done using the serviceActivations configuration section.

How to do it

WCF 3.x sample:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>

    <services>
      <service behaviorConfiguration="ServiceBehavior" name="WCF.wcfTestServiceImpl">
        <endpoint address="http://localhost:60063/TestService1.svc" binding="wsHttpBinding" contract="WCF.IwcfTestService"
 behaviorConfiguration=""/>
        <endpoint address="mex" bindingConfiguration="" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment>
      <serviceActivations>
        <add relativeAddress="WCF.wcfTestServiceImpl.svc" service="WCF.wcfTestServiceImpl"/>
      </serviceActivations>
    </serviceHostingEnvironment>

  </system.serviceModel>
</configuration>

WCF 4 sample (Simplified configuration):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment>
      <serviceActivations>
        <add relativeAddress="WCF.wcfTestServiceImpl.svc" service="WCF.wcfTestServiceImpl"/>
      </serviceActivations>
    </serviceHostingEnvironment>

  </system.serviceModel>
</configuration>
References

[1] Refer to  the Windows Communication Foundation (WCF) ServiceModel configuration elements article for details about each configuration secions

[2] Refer to the Configuring Client Behaviors article for details about of how to configure behavior in a file or programatically

[3] Refer to the Client Binding in Configuration article for details about of how to configure bindings in a file or programatically (Client side)

[4] Refer to the Service Binding in Configuration and Specify a Service Binding in Code articles for details about of how to configure bindings in a file or programatically (Service definition side)