Thursday 15 March 2012

How to deploy WCF Web Service on IIS

In my article "How to create and test WCF Web Service" I described how to create a simple WCF Web Service. Its natural host environment is Microsoft IIS web server. Here is the step-by-step guide how to deploy WCF Service on IIS.

Let us assume that c:\inetpub\wwwroot\WCFServices is a directory that will contain all our WCF Web Services. Build output of Calculator project was CalculatorServiceLibrary.dll and its configuration file, CalculatorServiceLibrary.dll.config.

Let us create directory for our Calculator service, with its subdirectory bin:

c:\inetpub\wwwroot\WCFServices\Calculator
c:\inetpub\wwwroot\WCFServices\Calculator\bin

Now we need to copy our service dll and config file:

c:\inetpub\wwwroot\WCFServices\Calculator\CalculatorServiceLibrary.dll.config
c:\inetpub\wwwroot\WCFServices\Calculator\bin\CalculatorServiceLibrary.dll

IIS requires config file to be named as web.config so we will rename our config file accordingly:

c:\inetpub\wwwroot\WCFServices\Calculator\web.config
c:\inetpub\wwwroot\WCFServices\Calculator\bin\CalculatorServiceLibrary.dll

The next step is creating a simple single-line document named service.svc:



Service name stated here must match the one from web.config (CalculatorServiceLibrary.dll.config).

Complete set of files is:

c:\inetpub\wwwroot\WCFServices\Calculator\web.config
c:\inetpub\wwwroot\WCFServices\Calculator\service.svc
c:\inetpub\wwwroot\WCFServices\Calculator\bin\CalculatorServiceLibrary.dll

In IIS Manager, under Default Web Site, find WCFServices directory and its subdirectory, Calculator. Select Calculator, right-click on it and click on Convert to Application item in the context menu. Web Application Settings dialog appears and we can leave default values:

IISManagement-Calculator-App-Settings

When we close this dialog box, a Web Application icon appears next to the directory name:

IISManagement-Calculator-App

Our web service is now deployed! We can check that by typing its URL (http://localhost/WCFServices/Calculator/Service.svc) in web browser:

WebBrowser-WebService-Calc

We can test web methods by using WCF Test Client:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfTestClient.exe http://bojan-pc/WCFServices/Calculator/service.svc/mex

If running IIS on local host, localhost name can be used in web service URL:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfTestClient.exe http://localhost/WCFServices/Calculator/service.svc/mex

WCF Web Client:

WCFTestClient-Calc-Add

Fiddler is able to capture IIS HTTP traffic by default:

Fidller-WS-on-IIS-Calc-Raw-View

If we are interested only in SOAP messages, we can use XML View in WCF Test Client:

WCFTestClient-Calc-Add-XMLView

How to sniff SOAP messages exchanged between WCF Service Host and Test Client

In my article "How to create and test WCF Web Service" I described how to implement simple Calculator service and test it from standalone WCF Service Host and Test Client.

SOAP Web Service and client exchange SOAP messages (request and response) during web method calls. SOAP messages are wrapped with HTTP messages and could be viewed and analysed by using some HTTP sniffer application.

For HTTP (SOAP) debugging I usually use Fiddler. It is a HTTP Proxy running on port 8888 on the local host. By default it intercepts HTTP traffic between web browsers and servers but can be set to sniff HTTP packets for any application that accepts HTTP proxies.

If we set Calculator web service to listen on port 8733 (defined in baseAddress URL in App.config) we can run WCF Service Host:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfSvcHost.exe /service:"c:\DEVELOPMENT\RESEARCH\C#\WCF\Web Services\CalculatorServiceLibrary\CalculatorServiceLibrary\bin\Debug\CalculatorServiceLibrary.dll" /config:"c:\DEVELOPMENT\RESEARCH\C#\WCF\Web Services\CalculatorServiceLibrary\CalculatorServiceLibrary\bin\Debug\CalculatorServiceLibrary.dll.config

...and Test Client:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfTestClient.exe http://localhost:8733/Design_Time_Addresses/CalculatorServiceLibrary/Service1/mex

Their model of communication is simple: Web Service Host listens on port 8733 for incoming SOAP requests (on service endpoint with URL http://localhost:8733/Design_Time_Addresses/CalculatorServiceLibrary/Service1) or metadata requests (on metadata endpoint with URL http://localhost:8733/Design_Time_Addresses/CalculatorServiceLibrary/Service1/mex). Once client sends request, host is loading Web Service dll, executing web method, packing result into SOAP response and sending it back within HTTP response:


WCF-host-clt-no-proxy


Fiddler is by default listening on port 8888 and in this constellation cannot intercept traffic between WCF Host and Client. We need to set it as a HTTP proxy which will forward all HTTP traffic to port where WCF Host is listening - port 8733. This can be achieved by adding ReverseProxyForPort DWORD value to HKCU\SOFTWARE\Microsoft\Fiddler2 and setting it to 8733. Fiddler must be restarted to fetch this change.

Client can send now HTTP requests to port 8888 in which case Fiddler will be able to intercept and display HTTP messages. It will forward them to port 8733 so they will reach Web Service Host. Of course, client can still send HTTP requests directly to port 8733, bypassing Fiddler.

When we run WCF Test Client we are providing it with metadata URL. This metadata contains service URL which is one defined in the service's App.config. This URL contains port number and it is set to 8733. Client will use this URL in order to make web service call. But how can we trick client so it uses port 8888 instead of 8733? When client gets metadata, it stores it in its own config file - client.dll.config. This file is stored in user's temporary folder, e.g. in c:\Users\Bojan\AppData\Local\Temp\Test Client Projects\10.0\636e9680-a905-4c50-a9ed-99562eb36701\ and looks something like this:

client.dll.config:


We can modify this config file before invoking web methods. We can do it manually through any text editor or simply from Test Client application. We can navigate client to target port 8888 now (make sure Fiddler is running - it listens on port 8888):

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfTestClient.exe http://localhost:8888/Design_Time_Addresses/CalculatorServiceLibrary/Service1/mex

WCF Test Client:

WCFTestClient-before-editing-endpoint-port

If we select and right click Config File node, a context menu appears with option Edit with SvcConfigEditor:

WCFTestClient-config-context-menu

If we click on it, Service Configuration Editor starts and loads client.dll.config:

WCFTestClient-config-editor

We can change port to 8888:

WCFTestClient-config-editor-after-editing

We can now invoke some web method, let's say Add:

WCFTestClient-invoke-add

Fiddler will capture exchanged HTTP messages and we can view their content (SOAP). This is a XML view:

Fidller-WCF-WS-Calc-XML-view

HTTP headers can be analysed in raw view:

Fidller-WCF-WS-Calc-Raw-View

This is the model of communication between WCF Test Client and Host via HTTP proxy we implemented above:


WCF-host-clt-Fiddler-proxy


Links and References:
Using Fiddler as a Reverse Proxy

How to create and test WCF Web Service

Implementing and testing web services in Visual Studio (2010) using Windows Communication Foundation (WCF) is very easy.

Let's say we want to create Calculator service which exposes methods that return results of addition, subtraction, multiplication and division applied on provided operands. These operations always take two operands so we can group them in a class Operands.



Now we can define interface of such web service:



Once we have have a clear image of exposed web methods and data types we can start implementing web service. In Visual Studio (I am using VS2010), go to File -> New -> Project... and create Visual C# WCF Service Library project named CalculatorServiceLibrary. Make sure you are using the latest .NET Framework (e.g. version 4.0). Visual Studio creates project skeleton with following files:

IService1.cs (service interface definition file):

Service1.cs (service interface implementation file):


App.config:


These auto-generated files give us a hint how to organize the code and we need to modify them, inserting specifics of our service.

WCF is a framework for building Service Oriented Architecture (SOA) applications. SOA requires defining protocols on messages and data exchanged between service and client. They are known as Service and Data Contracts and are supported by WCF.

Web Service interface definition file contains these contracts.

Service Contract defines operations exposed by the service. [ServiceContract] attribute applied to an interface (or class) tells it represents a service contract. Interface or class methods that are to be exposed as service operations are marked with [OperationContract] attribute.

Data exchanged between client and service (service operations arguments and return values) is described through Data Contract. All data is embedded into SOAP messages which are XML-based so data types must be serializable. All primitive .NET types are serializable by default and have default data contracts. But custom types that are part of data contract must be marked with [DataContract] attribute which defines them to be serializable. Type members that are part of data contract must be marked with [DataMember] attribute.

In our case, custom data type is class Operands and we need to mark it as [DataContract]. We can rename IService1.cs and Service1.cs to ICalculatorService.cs and CalculatorService.cs. After modifying the interface, its implementation class and data type, these files look like this:

ICalculatorService.cs:


CalculatorService.cs:


[ServiceBehavior] attribute controls various aspects of service object behaviour. In our case we specified that there will be only a single instance of the service object created on the server and that only a single thread at a time will be allowed to process method calls. This means that one client would need to wait for another's client web method call to complete. In our simple example this is acceptable but if amount of processing within web methods was higher, a different behaviour model would need to be applied.

Before compiling our project we yet need to modify application configuration file (App.config). Let us rename service to "CalculatorServiceLibrary.CalculatorService" and name behavior as "MetadataEnabled". In order to enable generating WSDL we need to add reference to this behavior as a service attribute: behaviorConfiguration="MetadataEnabled" and add httpGetUrl="mex" to behavior's serviceMetadata element. URL of the WSDL can now be made by appending "/mex" to the base address.

By default, service endpoint binding is set to wsHttpBinding which encrypts messages. For our convenience, as we will be using HTTP sniffer later, let us apply basicHttpBinding, which does not apply encryption. This way we will be able to see unencrypted data in HTTP messages exchanged between server and client.

Yet another thing set by default is to be changed: service endpoint contract - let us rename it to "CalculatorServiceLibrary.ICalculatorService".

App.config will have the final look:


We are now ready to build this project. If we build it in Debug mode, project's Debug directory will contain CalculatorServiceLibrary.dll and CalculatorServiceLibrary.dll.config. This config file is a pure copy of App.config visible and editable from Visual Studio.

We can test our web service from Visual Studio if we run the project (press F5 key). This will start WCF Service Host and WCF Test Client tools. Service will automatically be deployed on the host and the client will use published metadata information in order to build a list of web methods (matadata is fetched from endpoint that implements IMetadataExchange contract). We can type in arguments and invoke web methods in the Test Client.

WCF Service Host:

WCFSvcHost

WCF Test Client:

WCFTestClient

In order to see generated WSDL we can copy metadata address (WSDL URL; in our example: http://localhost:8732/Design_Time_Addresses/CalculatorServiceLibrary/Service1/mex) from Web Service Host and paste it into a web browser:

WSDL-WS-Calc

Generated WSDL for this service is:



We can run WCF Service Host out of Visual Studio, from command prompt:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfSvcHost.exe /service:"c:\DEVELOPMENT\RESEARCH\C#\WCF\Web Services\CalculatorServiceLibrary\CalculatorServiceLibrary\bin\Debug\CalculatorServiceLibrary.dll" /config:"c:\DEVELOPMENT\RESEARCH\C#\WCF\Web Services\CalculatorServiceLibrary\CalculatorServiceLibrary\bin\Debug\CalculatorServiceLibrary.dll.config"

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>

If this instance of the host cannot create endpoint (cannot listen) on the port 8732 (because previous instance run from Visual Studio has locked it), enter some other port number in baseAddress in App.config (e.g. 8733).

From another instance of cmd.exe, we can run WCF Test Client:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>WcfTestClient.exe http://localhost:8732/Design_Time_Addresses/CalculatorServiceLibrary/Service1/mex

Client and host exchange SOAP messages (request and response) during web method calls. We could see the content of those SOAP messages by using some HTTP sniffer. In my next article, "How to sniff SOAP messages exchanged between WCF Service Host and Test Client" I will describe how to set Fiddler Web Debugger in order to capture HTTP traffic between these two applications.

Links and References:

What Is Windows Communication Foundation (MSDN)
Windows Communication Foundation (Wikipedia)
Designing and Implementing Services (MSDN)
Using Data Contracts (MSDN)
Sessions, Instancing, and Concurrency (MSDN)