创建、托管(自托管、IIS 托管)和使用 WCF 服务






4.72/5 (27投票s)
创建、托管(自托管、IIS 托管)和使用 WCF 服务
什么是 WCF?
Windows Communication Foundation API 允许以这样的方式构建分布式体系结构:一旦创建,服务代码就可以被内部应用程序利用,该应用程序使用 TCP/IP 进行通信,Web 应用程序使用 HTTP 协议与 Web 服务通信,应用程序使用 MSMQ。WCF 服务也适用于 .NET Framework 之外开发的应用程序。
创建 WCF 服务
请按照下面列出的步骤创建服务。
步骤 1
在 Visual Studio 中创建服务。选择 C# 或 VB,然后选择项目类型 WCF 服务库或 WCF 服务网站项目模板。

第一个在编译后创建 *.dll 和 app.config 文件,您可以在宿主应用程序中使用这些文件并将服务公开给客户端。

第二个项目创建带有正确的 web.config 文件和 *.svc 文件,该文件通过虚拟目录直接托管在 IIS 上,并通过 HTTP 协议将服务公开给客户端。因此,服务无法公开给 Tclient。此选项的好处在于无需创建宿主应用程序,可以直接通过虚拟目录将其托管在 IIS 上。在此讨论中,我将首先创建一个 WCF 服务库,然后讨论 IIS 部署。
第二步
通过指定适当的属性创建契约。此契约告诉客户端服务公开了哪些方法以及服务公开的自定义类型。您可以使用 System.ServiceModel 命名空间中的属性列表来装饰您的契约。您可以创建自己的文件,或者在选择正确的项目类型后,它会为您的 Iservice.cs 和 Service.cs 创建两个文件。如果您要创建自己的文件,建议您创建接口并在类中实现它。
[ServiceContract]
- 定义参与提供的服务的接口。
[ServiceContract]
public interface IService1
{
....
}
[OperationContract]
- 定义服务将公开的方法。
[OperationContract]
string GetData(int value);
[DataMember]
- 定义通过服务公开的属性。
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataContract]
- 定义通过服务公开的自定义数据类型。
[DataContract]
public class CompositeType
{
...
}
完成 Web 服务创建后,您的代码应如下所示。
库 app.config 文件
此文件包含有关元数据交换的信息,定义了元数据的终结点。它还包含客户端与服务通信的终结点信息。终结点是 ABC,即地址、绑定和契约。如您在上面的配置文件中看到的,服务通过以下行公开以进行 TCP 通信
<system.serviceModel>
<services>
<service name="WcfServiceLibrary.Service1"
behaviorConfiguration="WcfServiceLibrary.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "https://:8080/Service1/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified,
address is relative to base address supplied above -->
<endpoint address="net.tcp://:9000/myservice"
binding="netTcpBinding" contract="WcfServiceLibrary.IService1">
</endpoint>
<endpoint address ="" binding="wsHttpBinding"
contract="WcfServiceLibrary.IService1">
<!--
Upon deployment, the following identity element
should be removed or replaced to reflect the
identity under which the deployed service runs.
If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service
to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and
should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary.Service1Behavior">
<!-- 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>
</system.serviceModel>
绑定详情: http://www.c-sharpcorner.com/UploadFile/pjthesedays/bindwcf05032009012251AM/bindwcf.aspx。
IService.Cs 文件
namespace WcfServiceLibrary
{
// NOTE: If you change the interface name "IService1" here,
// you must also update the reference to "IService1" in App.config.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add
// composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
Service.cs
namespace WcfServiceLibrary
{
// NOTE: If you change the class name "Service1" here,
// you must also update the reference to "Service1" in App.config.
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
托管 WCF 服务
- 自托管
- IIS 托管
- Windows 服务
- WAS
自托管和 IIS 托管演示。
自托管
步骤 1
创建新项目 >> 类库 >> 将此项目命名为 Host。

第二步
为宿主应用程序添加引用。右键单击“引用”>> “添加引用”。
步骤 3
在为宿主应用程序添加引用以向客户端公开 Web 服务以供使用后,正如您在下面的代码行中看到的,它创建了宿主对象,该对象是我们在 WCF 服务库项目中创建的 Service1 类型。
using (System.ServiceModel.ServiceHost host =
new System.ServiceModel.ServiceHost(typeof(Service1)))
{
}
如您所见,我们使用了 using 块,以便在关闭应用程序时处理宿主对象。
步骤 4
要启动服务以处理来自其服务客户端的请求,您需要调用 open 方法:
host.Open();
要停止接收请求,您需要调用 close 方法。
Host.cs
namespace HostApp
{
class Program
{
static void Main(string[] args)
{
using (System.ServiceModel.ServiceHost host =
new System.ServiceModel.ServiceHost(typeof(Service1)))
{
host.Open();
Console.WriteLine("Service started. press any key to stop it");
Console.ReadLine();
host.Close();
}
}
}
}
IIS 托管
- 要在应用程序中托管相同的 WCF 库,请使用 WCF Web 应用程序模板创建 WCF Web 应用程序项目,如我们开始时所讨论的。
- 删除 App_Code 文件夹中创建的 IService.cs 和 Service.cs 文件
- 包含我们创建的 WCF 库 *.dll 文件。
- 打开 Service.svc 文件并修改其中的单行。
<xmlns="http://www.w3.org/1999/xhtml"><xmlns="http://www.w3.org/1999/xhtml"> <%@ ServiceHost Language="C#" Debug="true" Service="WcfServiceLibrary.Service1" %>
更改 Web 服务 WEB.Config 文件以向客户端公开服务,即您需要创建与服务库的 app.config 文件中列出的元素相同的元素。
使用 WCF 服务
步骤 1
创建新项目 >> 类库 >> 将此项目命名为 Client,就像我们创建宿主应用程序一样。如果您想使用 Web 应用程序中托管的 Web 服务,请直接从下面的第 2 步开始。
第二步
通过右键单击项目 >> 添加服务引用来为客户端添加服务引用。

这将自动创建用于使用 Web 服务的代理文件,或者可以使用ServiceModel Metadata Utility Tool (Svcutil.exe),这是一个从元数据生成代理代码的命令行工具。
svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config
步骤 3
从客户端向服务发送请求
ServiceReference1.Service1Client client = new Client.ServiceReference1.Service1Client();
Console.WriteLine(client.GetData(5));
Console.ReadLine();
client.Close();
因此,正如您在上面的代码中看到的,您需要创建 Service1Client 对象,然后您可以轻松地调用 Service 公开的方法。如果您想查看自动生成的代码,请在 Service1Client 上按 F12,它会向您显示代理代码。
摘要
按照上面列出的步骤进行操作,创建、使用和托管 WCF 服务非常容易。