Hosting WCF Service in IIS


 

  


All right!! So I have created a WCF service and I want to consume it…what do I do? Where do I host the service? The first choice that comes to one’s mind (and which most of the examples talk about) is creating a console application and hosting the WCF service within this application. But this option is good only when you want to host the service quickly and test it out. In a practical scenario, we would require a service which sits there and is available all the time and allows a message based activation. Also, wouldn’t it be great if we can get rid of the extra code that we have to write just to host the service? Fortunately, WCF provides various options when it comes to hosting a service. These options are:


1.       Console application


2.       Winform application


3.       IIS


4.       Windows service


5.       Windows Activation Service.


Of course, the choice of the host restricts the type of transport that you can use for that service. I will not go into those details in this post. Let us look at how we can host the WCF service in IIS. When we use IIS to host WCF services, the services are integrated into ASP .NET. Thus the WCF services can take advantage of some of the inherent feature of ASP .NET such as process recycling, process health monitoring, message-based activation and idle shutdown. So let us get started…


Create a WCF service


1.       Create a blank solution and add a WCF Service Library project to it. For the purpose of this post, I am going to create a simple GreetingService that has a method Greet. This method accepts a single parameter name and returns a string “Hello “ appended to name


 


Add a WCF Service to the solution


 


2.       The following is the code for the GreetingService WCF service. We define a service contract, mark the operations in that contract that are going to be exposed to the external world and then implement the service.


 

  


using System;


using System.Collections.Generic;


using System.Text;


using System.ServiceModel;


 


namespace Wcf.Samples.ServiceLibrary


{


    [ServiceContract()]


    public interface IGreeting


    {


        [OperationContract()]


        string Greet(string name);


    }


}


GreetingService.cs


using System;


using System.Collections.Generic;


using System.Text;


 


namespace Wcf.Samples.ServiceLibrary


{


    public class GreetingService : IGreeting


    {


 


        #region IGreeting Members


 


        public string Greet(string name)


        {


            return “Hello – ” + name;


        }


 


        #endregion


    }


}


 


 

  


3.       Now that you added the service contract and its implementation (the GreetingService), build the project.


 


Host the service in IIS


1.       Now we create a Web site that will host the WCF service that we created in the previous section. For this, right-click the solution in the solution explorer and from the context menu, select Add -> New Web site  ->WCF Service as shown in the following figure.


 


Add a new WCF Service web-site


 


2.       This will create a WCF Service Web site into your solution along with the standard folders that get created for a Web site project (App_Code, App_Data etc). A new type of file called Service.svc will be generated and placed into the root of the Web site project, along with the corresponding code-behind file (Service.cs). The Service.cs is provided to implement a WCF service, which then can be referred in the Service.svc file. Since we already have created the WCF service in a separate assembly, we will refer to it in the Service.svc. As such we don’t need Service.cs and hence, it can be deleted.


3.       Open Service.svc file and modify the single line in it like this:


<%@ ServiceHost Language=”C#” Debug=”true” Service=”Wcf.Samples.ServiceLibrary.GreetingService” %>


4.       In the above statement we point to the fully-qualified class name that implements the service that we want to host in IIS.


5.       Add the reference of the Wcf.Samples.ServiceLibrary project to the web-site project and build the web-site.


6.       This completes the creation of WCF service. Now, in order to let the service communicate with the external world, we need to define the communication behavior of the service. For defining this behavior, we will use the Service Configuration tool that comes along with Visual Studio 2005.


7.       From the main menu of Visual Studio 2005, select Tools -> WCF Service Configuration Editor. The WCF Configuration Editor window will open up. Select File -> Open -> Config File… from the main menu. Browse and select the Web.config file of the WCF web-site.


8.       Once selected, the screen will be displayed as follows. The Web.config already has the configuration for the default service MyService under the Services node in the left-panel. Select this service and deleted it. We are going to create a new configuration for our service.


 


 


WCF Service Configuration Editor


 


9.       Right-click the Services node and select “New service” from the context menu. A service with service type NewServiceType will be created. On the right-panel, select the property “Name” and click the ellipsis. Service Type Browser will open up. Browse the bin folder of the web-site and locate the service assembly Wcf.Samples.ServiceLibrary and double-click it. The Service Type Browser dialog now will list the service “Wcf.Samples.ServiceLibrary.GreetingService” service. Select this service and click Open. This will set the service-type that we are going to configure.


10.   Now for the above service, we first need to specify the end-point. Right-click Endpoints node in the left-panel of the WCF Service Configuration Editor and select “New Endpoint”. This will create a default end-point with its properties being displayed in the right-panel.


11.   Set the following properties:


 
















Name


defaultEp


Address


http://localhost:28053/GreetingService/Service.svc


·         Here 28053 is the port-number where the local web-server is running. You need to check your port number and enter it here appropriately.


Binding


basicHttpBinding


Contract


Wcf.Samples.ServiceLibrary.IGreeting


·         You can click the ellipses to open the Contract Type Browser and select the appropriate assembly and contract from the bin directory of the web-site.


 


12.   This sets the basic communication for our service. In order to enable the service for metadata exchange (thereby allowing us the browse its wsdl), we need to set the metadata exchange properties for the service. To do this, expand the Advanced node in the left-panel, right-click Service Behaviors and select “New Service Behavior Configuration”. This will add a new Behavior Configuration by the default name NewBehavior. Behavior is a collection of attributes (here, service attributes) that can be set and applied to the service together. Right now, we are going to define a behavior that allows the metadata exchange on the service. Set the Name property of the new behavior configuration to mexBehavior.


13.   In the “Behavior element extension position” (lower part of the right-panel), click “Add” button. This opens up a dialog “Adding Behavior Element Extension Sections”. Select serviceMetadata from the list and click “Add” on the dialog. This adds the extension serviceMetadata to the grid in the right-panel. Double-click the extension to open up its property-page. Set the property HttpGetEnabled to true.


 


Setting the service behavior


 



 


14.   Now that we have defined the behavior separately, we need to associate the behavior with our service. To do this, select the Wcf.Samples.ServiceLibrary.GreetingService under the Services node in the left panel. The right-panel will display its properties. Select the BehaviorConfiguration property, and select “mexBehavior” from the drop-down.


15.   This sets the service configuration and allows the service to communicate with the external world. Save the configuration by selecting the menu File->Save. Close the WCF Service Configuration Editor.


16.   Test that the service is hosted by running the WCF Web Site application. The following screen should be displayed.


 


WCF Service Test page


 


You can test this service by creating a Console application and adding a proxy (generate the proxy by running the svcutil.exe utility). In the next post, I will explain how to invoke a WCF service hosted in IIS through the new WCF Adapter in BizTalk R2.


 


Till then… happy coding J


 


 


 

Comments (59)

  1. arun says:

    Good stuff!

  2. Jigar Mehta says:

    Thanks a lot for step by step instructions.

    Its really good when somebody is starting to program in WCF, like me!! 🙂

  3. With the new version of TeamGuide using a WCF service to distribute the Process MeNtOR content to our…

  4. kavit says:

    The contract name ‘Wcf.Samples.ServiceLibrary.IGreeting’ could not be found in the list of contracts implemented by the service ‘GreetingService’.

  5. kk says:

    Help meee….!!!!!!!!!!

    I am geeting error like this..

    The contract name ‘Wcf.Samples.ServiceLibrary.IGreeting’ could not be found in the list of contracts implemented by the service ‘GreetingService’.

  6. General says:

    I`m getting error

    No protocol binding matches the given address ‘http://localhost:8000/GreetingService/Service.svc‘. Protocol bindings are configured at the Site level in IIS or WAS configuration.

  7. seshadri says:

    Hi, if I add a new method in the service, then i removed service refference in the client and add a new reefference to that using service url. but it is accepting only old method in the proxy, i am unable to find my new method in the service. can you solve my problem. i have thought this due to caching. i have tried with new service project then my second method is accessing..

    Thanks in advance

    seshadri

  8. Divya says:

    Great stuff! THis works fine in VS2005(whish uses Cassini). If i try the same stuff in IIS 6.0 from my WIndows XP 64-bit, i get the error:

    HTTP Error 401.1 – Unauthorized: Access is denied due to invalid credentials.

    Internet Information Services (IIS)

    Not sure why because I even tried having the aspnet account with administrator priveleges. It would really help if you could give us detailed steps on what we need to do to have things running on IIS?

    Thanks for putting together this article in first place!

  9. Arvind Robin Kumar says:

    I got error when I host this in windows xp.

    Thanks in advance…

  10. Arvind Robin Kumar says:

    That too if it is placed in virtual directory, access denied kind of error came.

  11. Carlos DeAngulo says:

    Your example is great, and works perfect… however, in the step to create a Web site that will host the WCF service, you have selected the Location to create this website in the FileSystem rather than HTTP. If you run through this same example, and select HTTP the example does NOT work anymore. Can you please explain why, and do you know how to fix it? Thank you for your help and time.

  12. Ram says:

    Is it possible to initialize and access a global object which will be accessed by multiple client requests? Say for example, we want to know the inventory of an item in the ware house. Inventory of all items is read from database and stored in a global memory object during the first client request or creating the WCF host. Subsequently, if any user  logs in, WCF should access this global memory object and return the inventory for the item requested without reading from the database again.

    I am not able to initialize this object and each time a user requests comes, the whole process started all over again. Thanks in advance for your help

  13. gnobber says:

    Do you need to create an .svc file for each service that you want to host in IIS? If so, how would you go about extracting the combined proxies and config of each service?

  14. Arvind Kumar says:

    I made a WCF service library and use it in a wcf service but when i run this service i got the following error:

    There is no compatible TransportManager found for URI ‘http://localhost:2755/GreetingService/Service.svc‘. This may be because that you have used an absolute address which points outside of the virtual application. Please use a relative address instead.

    Can anyone help me to figure it out?

  15. Ramakrishnan says:

    Can you please let me know What is the difference between hosting the WCF application in IIS and other application?

  16. rohini says:

    hi,

    the article was nice.when i am trying to implement I`m getting this error

    No protocol binding matches the given address ‘http://localhost:8000/GreetingService/Service.svc‘. Protocol bindings are configured at the Site level in IIS or WAS configuration.

  17. rohini says:

    hi,

    the article was nice.when i am trying to implement I`m getting this error

    No protocol binding matches the given address ‘http://localhost:8000/GreetingService/Service.svc‘. Protocol bindings are configured at the Site level in IIS or WAS configuration.

    please help me in that

  18. surresh says:

    sir,how to consume the wcf service using asp.net

  19. Ehsan says:

    To add a little more to this great thread is to publish the service in an IIS VD and then using it just a we use an ASMX file and consume it in an asp .net app by web refrencing it.  If we use the publishing route, we have to update the end point not to enclude the port number in its configuration.

  20. Andrew says:

    I also get the same issue that other readers mentioned. Is it something to do with IIS pointing to the wrong version of the Framework? Mine appears to point to 2.0, but 3/3.5 isn’t available in the dropdown list.

    No protocol binding matches the given address ‘http://localhost/GreetingService/Service.svc‘. Protocol bindings are configured at the Site level in IIS or WAS configuration.

  21. Tim W says:

    No protocol binding error is normally due to your configurations (both server and client).  The server will use a binding like basicHttp and your client should use the same.  

  22. Ravindra Dewangan says:

    Oops !!! "Server Application Unavailable" error page when tried navigating to the "Services.svc" file in the service’s virtual directory, through browser.

    Later, registed the apsnet_wp (using aspnet_regiis -i -enable) for .Net 2.0 and it goes well.

  23. Priya says:

    Thanks a lot for the details.

    Very informative

  24. alik levin's says:

    This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case

  25. Bipin says:

    This is a very good article… as a starting i found it very usefull..

    Can u plz help me on Hosting MSMQ service.

    Because endpoint get changed here..same for protocol..

    Thanks !

  26. 江南白衣 says:

    This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case it is useful.

  27. bache says:

    I was getting the same error message "No protocol binding matches the given address ‘http://localhost:8000/GreetingService/Service.svc‘. Protocol bindings are configured at the Site level in IIS or WAS configuration." as General and rohini.

    The problem was that this address http://localhost:8000/GreetingService/Service.svc was different from the address specified in the web.config in endpoint section. So check your web.config. You can configure the website not to use the default Web server but to use IIS in the properties of the website.

    Thank you for the tutorial!

  28. Thirumal says:

    How can we use IPC binding to host a service in WAS

  29. YourMomma says:

    Remove any addresses from your web.config, address="" and mex address="mex"

    Let IIS set the URI based on where you place the files.

  30. cvetan says:

    Thank you, that helped me a lot 🙂

  31. Aditya k says:

    Hi, Amit this article was really useful and easy to understand.

  32. Charly says:

    Hi,

    are there any restrictions when an iis wcf service consumes other wcf services?

    client -> wcf service (iis, http) -> wcf service (self hosted, net.tcp/named pipe)

    Can I use any communication protocol between the 2 wcf services?

  33. Ashutosh says:

    Hi,

    Nice Article. In VS 2008 we have a project template called "WCF Service Application".

    Thanks,

    Ashutosh

  34. Jeff says:

    gnobber, I noticed you were also wondering about whether the .svc files are necessary in IIS. So far I’m also unable to find the solution to this question. I’ll be posting any follow up to this question as part the topic I posted up on the MSDN forums.

    How do I expose WCF web services in IIS without using .svc files?

    http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/13c10940-e705-4c7e-8494-b28dac3b95e4

  35. dev says:

    hello

    I have a service that do this:

       public bool AuthenticateUser(string strUserName, int nPasswordHash)

    It’s called from ASP.NET login page. Executed the code with debugger running on Visual Studio and no exception. However when I view with "SvcTraceViewer", I keep seeing:

      "The body of the message cannot be read because it is empty."

    Here’s web.config of web service exposing authentication service:

    <?xml version="1.0"?>

    … more …

    &lt;system.serviceModel&gt;
    
        &lt;diagnostics&gt;
    

      <messageLogging logEntireMessage="true" logMalformedMessages="true"

       logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />

     </diagnostics>

     <services>

      <service behaviorConfiguration="ServiceBehavior" name="xxxxx.SecurityServiceLib.SecurityService">

         &lt;endpoint address=&quot;&quot;
    

           binding="basicHttpBinding"

           bindingConfiguration=""

           name="Basic"

           contract="xxxxx.SecurityServiceLib.ISecurityService">

        &lt;/endpoint&gt;
    

       <endpoint  address="MEX"

           binding="mexHttpBinding"

           name="MEX"

           contract="IMetadataExchange" />

       <host>

        <baseAddresses>

                &lt;add baseAddress=&quot;<a rel="nofollow" target="_new" href="http://localhost:18000/SecurityServiceWeb/&quot;">http://localhost:18000/SecurityServiceWeb/&quot;</a> /&gt;
    

        </baseAddresses>

        <timeouts closeTimeout="00:01:10" />

       </host>

      </service>

     </services>

        &lt;behaviors&gt;
    

      <serviceBehaviors>

       <behavior name="ServiceBehavior">

        <serviceMetadata httpGetEnabled="true" httpGetUrl="" />

        <serviceDebug includeExceptionDetailInFaults="true" />

       </behavior>

      </serviceBehaviors>

     </behaviors>

    &lt;/system.serviceModel&gt;
    

    … more …

    </configuration>

    Any idea? I been banging my head against the wall because of this for sometime and still bit stuck.

    dev

  36. Vicky Wauters says:

    Thanks for this step-by-step explaination.

    It helped me alot in understanding WCF Services.

    Great blog !!!

  37. kumar says:

    very good article for beginners…..

  38. Rithika says:

    I am getting the following error while browsing a WCF Service published on IIS

    Module: IIS Web Core

    Notification: BeginRequest

    Handler: Not yet determined

    Error Code: 0x800700b7

    Config Error: Cannot add duplicate collection entry of type ‘add’ with unique key attribute ‘name’ set to ‘ScriptHandlerFactory’  

    Config File: \?C:UsersAdministratorDesktopCS-CatalogCS WebServiceweb.config

    Requested URL: http://localhost:100/CS Service/CatalogManager.svc

    Physical Path: C:UsersAdministratorDesktopCS-CatalogCS WebServiceCatalogManager.svc

    Logon Method: Not yet determined

    Logon User: Not yet determined

    <remove name="WebServiceHandlerFactory-Integrated"/>

     134: <add name="ScriptHandlerFactory" verb="" path=".asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

     135: <add name="ScriptHandlerFactoryAppServices" verb="" path="_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

    There are no duplicate entries in the config file. Can anyone help me if have faced similar issues before

  39. Rohit gupta says:

    How can i stop my wcf service which is hosted in IIS

  40. Rohit gupta says:

    hOW TO STOP WCF SERVICE HOSTED BY IIS

  41. dC says:

    run Internet Information Services from Control Panel and hit the stop icon at the proper WCF Service

  42. Sachin Puri says:

    It is a tremendous article. a beginner in MCF cant get more than this. Keep going.

  43. tester says:

    Hi,

    It is a good article about how to create a WCF service and run in VS. However, I’d expect the detailed steps of how to copy/install/deploy it to IIS (what directories should be created, what configuration should be set etc.) By this, its title is very misleading.

  44. ashish says:

    can we host wcf service on port 80 in IIS 5.1  (windows xp SP2)?

  45. Nani says:

    Is web.config file and client config file in WCF are the same?

  46. upendra says:

    re: how to enhance a running serverice without interupt

  47. Jivan says:

    Thanks for your helpful solution. I receive the folowing error when i take the service reference

    <?xml version="1.0" encoding="utf-16"?><Fault xmlns="http://www.w3.org/2003/05/soap-envelope"><Code><Value>Sender</Value><Subcode><Value xmlns:a="http://schemas.xmlsoap.org/ws/2005/02/sc">a:BadContextToken</Value></Subcode></Code><Reason><Text xml:lang="en-GB">The message could not be processed. This is most likely because the action ‘http://schemas.xmlsoap.org/ws/2004/09/transfer/Get‘ is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint’s binding.</Text></Reason></Fault>

    HTTP GET Error

       URI: http://localhost/webwcfserver/service.svc

       The HTML document does not contain Web service discovery information.

  48. JF says:

    I was stuck when i publish on IIS until i found i had to change the asp.net version in "properties/asp.net"….

  49. rajee says:

    Solution for all possible Erros in the above example. (Classnames changed)

    ——————–ERRORS————————-

    1

    Any – Protocol bindings are configured at the Site level in IIS or WAS configuration

    2

    There is no compatible TransportManager found for URI ‘http://localhost:2626/EmployeeService/service.svc‘. This may

    be because that you have used an absolute address which points outside of the virtual application. Please use a

    relative address instead.

    3 (endpoint blank)

    A binding instance has already been associated to listen URI ‘http://localhost:2626/WCF1/Service.svc‘. If two

    endpoints want to share the same ListenUri, they must also share the same binding object instance. The two

    conflicting endpoints were either specified in AddServiceEndpoint() calls, in a config file, or a combination of

    AddServiceEndpoint() and config.

    ——————Error Web.config file—————

    <services>

            &lt;service behaviorConfiguration=&quot;mexBehavior&quot; name=&quot;WcfServiceLibrary1.EmployeeService&quot;&gt;
    
                &lt;endpoint address=&quot;&quot; binding=&quot;wsHttpBinding&quot; contract=&quot;WcfServiceLibrary1.IEmployeeService&quot;&gt;
    
                    &lt;identity&gt;
    
                        &lt;dns value=&quot;localhost&quot;/&gt;
    
                    &lt;/identity&gt;
    
                &lt;/endpoint&gt;
    
                &lt;endpoint address=&quot;mex&quot; binding=&quot;mexHttpBinding&quot; contract=&quot;IMetadataExchange&quot;/&gt;
    
                &lt;endpoint address=&quot;<a rel="nofollow" target="_new" href="http://localhost:2626/EmployeeService/service.svc">http://localhost:2626/EmployeeService/service.svc</a>&quot; binding=&quot;basicHttpBinding&quot; contract=&quot;WcfServiceLibrary1.IEmployeeService&quot;/&gt;
    
            &lt;/service&gt;
    
        &lt;/services&gt;
    

    —————————– Correct Web.Config file———————-

  50. rajee- rajeshram79([at])gmail.com says:

    —————————– Correct Web.Config file———————- Continues-…

    <services>

            &lt;service behaviorConfiguration=&quot;mexBehavior&quot; name=&quot;WcfServiceLibrary1.EmployeeService&quot;&gt;
    
                &lt;endpoint address=&quot;&quot; binding=&quot;basicHttpBinding&quot; contract=&quot;WcfServiceLibrary1.IEmployeeService&quot;/&gt;
    
            &lt;/service&gt;
    

    —–Fact————–

    Do not have multiple Endpoints.

    Do not confuse the IIS by hardcoding Adress/Port Number ect.

    Let endpoint Address be blank and IIS resolve the address automatically

  51. Nageswar says:

    Its Very cool…I loved it…Tanks …..

  52. Chandresh Patel says:

    Really Good one stuff……………..

    Highly Appriciate with this Artical……………….

    Thanks,

    Chandresh Patel

  53. Mohammed Haq says:

    Really nice and easy to understand post.

    Thanks a Lot.

  54. Create WCF Service and Host it in IIS says:

    More walkthrough on how to actually create WCF service and then host it in IIS is here

    technologyriver.blogspot.com/…/prerequisites-check-windows-7.html