Host WCF Service and ASP.NET Application on Same Virtual Directory
One of nice things about Windows Communication Foundation is its services can be hosted in IIS with an ASP.NET application with same virtual directory. This lets you to have a service for public usage and let your ASP.NET application to be its first client. In this implementation you share same configuration file for the service and ASP.NET application.
In this post I walk through an example of hosting a Windows Communication Foundation service and ASP.NET application in same virtual directory.
Write, Configure and Host a Service
First I create a Windows Communication Foundation service to host it in IIS. This service is very simple. It just provides a method that gets a DateTime parameter and calculates and returns the number of days between current date and given date. Later in ASP.NET application, user can enter his birthday to know how many days are passed from his or her life. In order to have simple structure on my server and avoid confusion between my WCF service and ASP.NET application files, I compile my service into an assembly and put it on server. Note that I can put my class file directly there but discipline is an important rule in development!
So I start with creating a simple service named DiffService which implements IDateDiffService service contract:
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
namespace DateDiffService
{
[ServiceContract()]
public interface IDateDiffService
{
[OperationContract]
int GetDateDiff(DateTime date);
}
public class DiffService : IDateDiffService
{
#region IDateDiffService Members
public int GetDateDiff(DateTime date)
{
TimeSpan diff = DateTime.Now.Subtract(date);
return diff.Days;
}
#endregion
}
}
Now I compile this service into DateDiffService assembly and create a configuration file for it. This configuration file is temporary and I will merge it with my ASP.NET application (my client) later.
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="DateDiffService.DiffService"
behaviorConfiguration="metadataSupport">
<endpoint contract="DateDiffService.IDateDiffService"
binding="wsHttpBinding"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="metadataSupport">
<serviceMetadata />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
After this, I create a virtual directory (named MyService) in IIS to host my service and ASP.NET application. If you're hosting the service in IIS 7.0, it's possible to get some errors. I may write (actually gather some information) about hosting WCF applications in IIS 7.0 in a future post.
It's time to create a .SVC file for my service (service.svc) as you see:
<%@ServiceHost language="c#" Debug="true" Service="DateDiffService.DiffService" %>
<%@Assembly Name="DateDiffService" %>
Having an assembly, a configuration file and .SVC file, I can put my service on the server and test it with browser (it's going to be a tutorial not a blog post):
So far so good! Let's get in client side!
Write, Configure and Host an ASP.NET Application
First thing that I need is a proxy based on my service. So I run svcutil command to create my proxy.
svcutil http://localhost/myservice/service.svc /out:proxy.cs
Now I create an ASP.NET application and copy my proxy file into its App_Code folder, make a reference to System.ServiceModel and add a textbox, A button and a label to my webpage. User enters his birthday in textbox, clicks on button and gets the output in label. Code logic for my button click is as simple as this:
protected void btnSend_Click(object sender, EventArgs e)
{
DateTime birthDate = DateTime.Parse(txtInput.Text);
int diff;
using (DateDiffServiceClient client = new DateDiffServiceClient())
{
client.Open();
diff = client.GetDateDiff(birthDate);
client.Close();
}
lblResult.Text = string.Format("You've passed {0} days in your life!", diff);
}
What's next?! A configuration file for my ASP.NET application. But it's a WCF client and needs something more than regular configuration elements. Thankfully svcutil creates all configurations for me in a separate file and I just need to put this code into the auto-generated Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IDateDiffService"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
bypassProxyOnLocal="false"
transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text"
textEncoding="utf-8"
useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32"
maxStringContentLength="8192"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<reliableSession ordered="true"
inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows"
proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows"
negotiateServiceCredential="true"
algorithmSuite="Default"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://keyvan-pc/MyService/service.svc"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IDateDiffService"
contract="IDateDiffService"
name="WSHttpBinding_IDateDiffService">
<identity>
<servicePrincipalName value="host/Keyvan-PC" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
I put all my ASP.NET files on server except Web.Config because I need to merge it with configuration file for service before deployment.
Merge Configuration Files
As I'm hosting both service and client on same place, I need to merge their configuration files into one single file. I skip showing this file because it's too long and is its main parts are presented before. After merging I put this configuration file in root of my virtual directory.
Test
I'm close to use my service via the client (ASP.NET application). By navigating to http://localhost/myservice I'll be able to do this.
Yes, 8131 days! I had to write this 132 days ago to celebrate 8000th days! Three years ago I used DateDiff function in Visual Basic to celebrate 7000th day!
Source codes for service and client are attached to this post.
[advertisement] Axosoft OnTime 2008 is four developer tools in one: bug tracking, project wiki, feature management, and help desk. It manages your development process so developers can focus on coding. Installed or Hosted – Free Single-user license -- Free 30-day team trial.
3 Comments : 01.15.07
Feedbacks
THis is good tutorial/article but you forgot to mention where to put the assembly file (in which folder or sub folder under IIS etc). I am sure many users of this tutorial get error that assembly not found.

#1
DotNetKicks.com
01.15.2007 @ 5:45 AM