MSDN 原文:
承载服务:http://msdn.microsoft.com/zh-cn/library/ms730158
托管应用程序中的自承载(如上一篇WCF入门中演示的那样);托管Windows服务(用Installutil.exe 安装);IIS(本文);WAS(Windows进程激活服务)
如何:在IIS中承载WCF服务 http://msdn.microsoft.com/zh-cn/library/ms733766
本文基本上是摘抄上文“如何:在IIS中承载WCF服务”,对配置文件修改了一点,原文的会出错。
1. 创建 IISHostedCalcService 文件夹;在IIS中创建应用,指向此目录,别名为:IISHostedCalc。
2. 在IISHostedCalcService下创建 service.svc文件(WCF服务文件),内容:
%@ServiceHost language="c#" Debug="true" Service="Microsoft.ServiceModel.Samples.CalculatorService"%
.svc文件包含WCF特定的处理指令@ServiceHost,该指令允许WCF承载基础机构激活所承载的服务,以相应传入消息。
3. 在 IISHostedCalcService 下创建App_Code子目录,创建Service.cs文件,内容:
using System;
using System.ServiceModel;
namespace Microsoft.ServiceModel.Samples
{
//Define a service contract
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
//Create the method declaration for the contract
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Substract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
/// <summary>
/// Create service class that implements the service contract
/// </summary>
public class CalculatorService : ICalculator
{
#region ICalculator Members
// Implement functionality for the service operations.
double ICalculator.Add(double n1, double n2)
{
return n1 + n2;
}
double ICalculator.Substract(double n1, double n2)
{
return n1 - n2;
}
double ICalculator.Multiply(double n1, double n2)
{
return n1 * n2;
}
double ICalculator.Divide(double n1, double n2)
{
return n1 / n2;
}
#endregion
}
}
对App_Code目录中文件进行的任何更改都会导致在收到下一个请求时回收和重新编译整个应用程序。
实现代码也可以按内联方式位于.svc文件中,@ServiceHost指令之后。
4. 在IISHostedCalcService下创建 Web.config,内容:(与MSDN原文相比,多了<behaviors>,否则在IE中会出现:Metadata publishing for this service is currently disabled.)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Microsoft.ServiceModel.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehaviors">
<!-- This endpoint is exposed at the base address provided by host:http://localhost/servicemodelsamples/service.svc -->
<endpoint address=""
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
<!-- The mex endpoint is explosed at http://localhost/servicemodelsamples/service.svc/mex -->
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehaviors" >
<!-- Without this config: Metadata publishing for this service is currently disabled. -->
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
5. 在IE中输入:http://localhost/IISHostedCalc/Service.svc
关于如何创建访问服务的客户端,参加上一篇《WCF入门》。