Friday, April 29, 2011

C#: Hosting an WCF application in IIS 7

I need to host an WCF application in IIS 7 under Window Servers 2008 R2. There are several steps needed to follow.

Create an WCF project in Visual Studio 2010



After creating a project WcfService, there are IWCFService.cs, WCFService.svc, WCFService.svc.cs and web.config in the solution.

For IWCFService.cs, you need to declare methods and customer data type.

namespace WcfService
{
     [ServiceContract]
     public interface IWCFService
     {
           [OperationContract]
           People SayHello();
     }
     [DataContract]
     public class People
     {
           [DataMember]
           public String id {get; set;}
           public String name {get; set;}
      }
}

For WCFService.svc.cs, you need to create the method declared in Operation Contract.

namespace WcfService
{
     public class WCFService: IWCFService
     {
           public People SayHello()
           {
                 return new People() {
                          id = "1",
                          name = "name"
                 };
            }
      }
}
For web.config, in order to host in IIS 7, it needs some configurations.


<?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service behaviorConfiguration="CustomerServiceBehavior" name="WcfService.WCFService"> <endpoint address="" binding="wsHttpBinding" contract="WcfService.IWCFService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="CustomerServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <directoryBrowse enabled="true"/> </system.webServer> <system.web> <compilation debug="true"/></system.web></configuration>
For WCFService.svc, by default, you need not modify it.

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService.WCFService" CodeBehind="WCFSevice.svc.cs" %>
Debugging Tool
It is quite difficult to do debugging in WCF application. Visual Studio 2010 provides a WCF Testclient interface for developer to invoke menthods.


Configure the file permission for IIS
In order to host the project in IIS, it require to access information inside. You need to select the project folder and then right click "Properties". Under tab "Security", add IIS_IUSERS and assign read permission to it.


Hosting the project in IIS 7
Under IIS, right click folder "Sites" and select "Add Web Site..."


If your application runs under .Net 4.0 version, you need to go to application. Click the application and then click "Advanced Settings..."  to update ".Net Framework Version" to v4.0


Last but not least, you need to restart the web site.

No comments:

Post a Comment