上一章讲述托管(Hosting)的基础知识,这一章我们主要介绍IIS托管。在IIS中托管服务与经典的ASMX Web服务托管相似,需要在IIS下创建虚拟目录,并提供一个.svc文件。.svc文件与.asmx文件相似,主要用于识别隐藏文件和类后面的服务代码。使用IIS托管,服务的基地址必须与.svc文件的地址保存一致。IIS除IIS7在启用WAS激活服务外只支持HTTP/HTTPS传输协议,根据IIS所支持的协议,我们可以采用的绑定(绑定的详细介绍请参考:WCF面向服务应用程序系列之八:绑定-基本知识)方式有:BasicHttpBinding、WSHttpBinding、WSDualHttpBinding,这里我们能过一个DEMO来介绍IIS托管。
开发环境:Visual Studio 2010 + Net Framework 4.0 。
1、创建一个WCF Service Library,主要代码如下:
namespace ServiceLibrary
{
public class HelloWCF : IHelloWCF
{
public string GetMessage(string msg)
{
return string.Format("The server received message is : {0}", msg);
}
}
}
2、创建一个WCF Service网站,删除自动生成的代码,添加上面的项目引用ServiceLibrary,并添加一个HelloWCFService.svc文件,修改Web.config文件。
HelloWCFService.svc内容如下:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="ServiceLibrary.HelloWCF">
<endpoint address="basicHttp" binding="basicHttpBinding" contract="ServiceLibrary.IHelloWCF" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
class Program
{
static void Main(string[] args)
{
using(Server.HelloWCFClient client = new Server.HelloWCFClient())
{
Console.WriteLine("------------Begin-------------");
Console.WriteLine(client.GetMessage("Hello WCF!"));
Console.WriteLine("------------End---------------");
}
Console.ReadLine();
}
}
5、编译Client项目,设置为启动项,然后Ctrl+F5(或者运行Client.exe)启动项目(此前的项目我们是通过F5来启动服务端与客户端,而此时我们的服务端托管在IIS,当我们访问服务地址时服务会自动启动),则可以看到如下输入:
------------Begin-------------
The server received message is : Hello WCF!
------------End---------------
至此,托管(Hosting)-IIS托管介绍完毕,下一章我们介绍自托管(Self-Hosting)。
点此下载DEMO。