以IIS为宿主发布WCF Service


好处
:采用以IIS作为宿主,就不必为Service专门建立一个host程序,部署也相对容易一些。

首先准备好测试用的WCF程序,这个例子只是做简单的求和计算,代码如下:


CalculatorService.svc
(服务文件):

<%@ServiceHost Language=”C#” Debug="True" Service=" OwenZhang.WcfSamples.CalculatorService"%>


ICalculator.cs
(定义服务契约):

[ServiceContract]
public interface ICalculator
{
   [OperationContract]
   
int Add(int n, int m);
}


CalculatorService.cs
(执行服务契约):

public class CalculatorService : ICalculator
{
   
public int Add(int n, int m)
   {
      
return n + m;
   }
}


注意: 假如你新建的项目类型是WebSite的话,ICalculator.csCalculatorService.cs文件位于App_Code文件夹下面。同样CalculatorService.svc要加上CodeBehind="~/App_Code/CalculatorService.cs"。


Web.config文件中添加endpoint:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<system.serviceModel>
    
<services>
      
<service name="OwenZhang.WcfSamples.CalculatorService">
        
<endpoint address="" binding="wsHttpBinding" contract="OwenZhang.WcfSamples.Samples.ICalculator" />
      
</service>
    
</services>
  
</system.serviceModel>
</configuration>


然后,在IIS中新建网站或虚拟目录,这我们在系统默认网站下面建立虚拟目录“C:\inetpub\wwwroot\CalculatorService”,然后将程序编译后的文件拷贝到CalculatorService目录中,就可以通过endpoint调用该服务了。

注意:假如你使用的是IIS 7.0(Windows Vista、Windows Server 2008环境),请确认WCF Activation(Server Manager->Features-> .NET Framework 3.0 Features)中的HTTP Activation(HTTP)和Non-HTTP Activation(Message Queuing,TCP和Named Pipes)已经安装上了,否则加载相关的服务会失败。另外,假如IIS中缺少识别.svc类型文件的应用程序扩展映射的话,你需要手动加上。

posted on 2008-05-13 21:11  Owen_Zhang  阅读(1439)  评论(1编辑  收藏  举报