WCF (. 4) of a first program WCF

I. Introduction

  Previous articles to share several other distributed technologies .NET platform, but in front of several distributed technology to focus on a particular field, and have different programming interfaces, which allows developers need to master the use of multiple API. Based on this reason, Microsoft has achieved in WCF 3.0 .NET. WCF is the integration of various technologies distributed under the .NET platform, distributed technology it will introduce several previously fully integrated, and provides a unified programming interface (API). For developers who only need to master a set of WCF API, you can implement a distributed technology before all functions implemented.

Two, WCF details

   WCF (Windows Communication Foundation) is a Microsoft unified programming model for building service-oriented applications (SOA) provided by means of the model, so that the building distributed systems, without the need to consider how to achieve communication-related issues, the developers pay more attention to implementation and business logic itself. In WCF, communication between the respective Application by Endpoint (endpoint) to achieve. The following details under WCF several important concepts.

2.1 EndPoint Details

   Service providers will publish consumer service to potential consumers through one or more service endpoint, the consumption of services is performed by matching the service endpoint. By the endpoint address (Address), three elements bindings (Binding) and contract (Contract) components. As shown below. Because of their initials are A, B, C. So there: EndPoint = ABC.

  These three factors play a role in the WCF communication are:

  • Address (Address) : address identifies the location of the service, to provide information and assistance service to identify the true identity of addressing. Address solve Where the WCF service? Problems.

  • Binding (the Binding) : Binding implements all the details of the communication, network transmission, message encoding, and other processing to achieve a certain function corresponding to the message, such as security features, and reliable transmission of affairs. WCF system having a series of binding defined as BasicHttpBinding, WsHttpBinding, NetTcpBinding like. Binding resolved How to Communicate with Service? The problem.

  • Contract (Contract) : service contract is for the operation of the abstract, also the definition of message exchange patterns and message structure. WCF contract can be divided into two categories, one is a description of the service operation; the other is a description of the data. Service contract (Service Contract) belong to the description of the operation of the service, and then to rest 3 comprises a Class Contract: The contract data (Data Contract), the contract message (Message Contract) and fault contract (Fault Contract). Contract solves What function does the Service Provide? Problems.

2.2 WCF basic concepts

  • Message mode

  A separate message data unit, it may consist of several components, including a message header and a message body. WCF supports multiple modes message, comprising a request - the recovery, and the one-way duplex communication. Different transport protocol supports message mode, WCF API and runtime can ensure safe and reliable to send a message

  • Communication protocols and coding

  WCF supports Http, TCP, Peer network (peer), IPC (named pipes based on internal process communication) and MSMQ protocol. Before performing message delivery, formatting must be encoded for a given message, WCF provides dedicated three kinds of coding options: one is a text encoding, an encoding across the platform; one is the Message Transmission Optimization Mechanism (MOMO) encoding the encoding for efficiently transmitting unstructured binary data to or receive service data from the service. One is for efficient transfer of binary coding.

  • Behavior (Behavior): Behavior main role is to do some of the behavior of custom EndPoint at runtime. For example, set the TimeOut property Callback Service Client.

  • Host and host processes: service must be carried in a process, the host process is an application designed specifically for bearer services, which include Internet Information Services host process (ie IIS), Windows Activation Service (WAS), Windows services. Lifecycle Services by the host control.

  • Self-hosted services: In addition to the service can be carried by the existing host process, but also can be self-supporting, self-hosted application service process is created by the developer to carry the service. The control application lifecycle services, set properties and services, and service opening and closing operations services.

Third, create the first WCF applications

   Introduced in front of the details of the WCF, Next, we use the following two methods to create a WCF service is hosted applications.

  • By self-boarding (Self-Hosting) manner, i.e., from the bearer service. Create a console application to serve as the host of.

  • By the way IIS boarding service hosted in IIS. Client to impersonate the client by another console program to a service call.

  Next, we go step by step There are two ways to achieve our WCF applications. First introduced to achieve self-boarding step of the way.

 Step one: create a service contract and service

  Since it is a distributed application, first, the first step must be to create a service application for other consumer spending. The WCF-based interaction to achieve a loose coupling between contract services of self-government, as well as client and server. From a functional point of view, all the abstract service contract operations services provided, so we generally defined by the form of service contract interface. By applying System.ServiceModel.Service.ServiceContractAttribute WCF features on the interface interface definition into a service contract. While application of this feature, you can also specify the service contract name and namespace, in the service contract, we will contract name and namespace set to HellworldService and http://www.Learninghard.com. After application of the characteristics of the interface defined ServiceContractAttribute service contract, the method defined in the interface can not automatically become the method of operating the service. In this case, we need to apply OperationContractAttribute characteristics explicitly on the respective method. Specific service contract implementation code is shown below:

1 [ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")]
2 public interface IHelloWorld
3 {
4 [OperationContract()]
5 string GetHelloWorld();
6 }

  After the service contract is successfully created, we need to implement specific service contract to create the WCF service. DETAILED WCF service implementation code is shown below:

1 public class HelloWorldService : IHelloWorld
2 {
3 public string GetHelloWorld()
4 {
5 return "Hello World";
6 }
7 }

Step Two: Create a service host

  Introduction to the front, WCF service must be registered in a process, the process is called the host application. The purpose is to open a boarding service processes to provide a runtime environment for WCF service. By adding one or more endpoints for the service, exposing it to the service consumers. Service consumer then matched by appropriate endpoint for service calls, to achieve the following WCF service by creating a self-boarding program console mode, the specific implementation code as follows:

1 using Contract;
2 using Services;
3 using System;
4 using System.ServiceModel;
5 using System.ServiceModel.Description;
6
7 namespace Hosting
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 using (ServiceHost host = new ServiceHost(typeof(HelloWorldService)))
14 {
15 // 如果采用配置文件的方式,Region中代码就可以注释点
16 #region
17 host.AddServiceEndpoint(typeof(IHelloWorld), new WSHttpBinding(), "http://127.0.0.1:8888/HelloWorldService");
18 if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
19 {
20 ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
Behavior.HttpGetEnabled to true = 21 is;
22 is behavior.HttpGetUrl = new new Uri ( "http://127.0.0.1:8888/HelloWorldService/metadata");
23 is host.Description.Behaviors.Add (behavior);
24}
25 #endregion
26 is
the delegate host.Opened + = 27
28 {
29 Console.WriteLine ( "the HelloWorldService has started, press any key to terminate the service!");
30};
31 is
32 host.Open ();
33 is Console.Read ();
34 is}
35}
36}
37}

  WCF service is hosted by ServiceHost objects to complete. In the above code, WCF instance is created by the WCF-based service type (typeof (HelloWorldService)), and by adding a AddServiceEndpoint endpoint, the endpoint addresses for the particular http://127.0.0.1:8888/HelloWorldService binding (binding) used type WSHttpBinding, and specify the type of service contract IHelloWorld.

  WCF is the realization of SOA, providing the basic characteristics of SOA are loosely coupled, loosely coupled applications WCF client and server is reflected in the client need to know basic WCF service description, without having to know the specific implementation details can be achieved on access to the service. Description WCF services by publishing the form of metadata. WCF is published metadata is ServiceMetadataBehavior achieved by a service behavior. In the above code, we add ServiceHost object created a ServiceMetadataBehavior, and uses the acquired metadata-based Http-GET way, metadata publishing address specified as http://127.0.0.1:8888/HelloWorldService/metadata. You can get in the Open method call ServiceHost for boarding after the success of the service through the address metadata related services, as Web services to get a description of the Web service WSDL as by entering an address. When we ConsoleAppHosting host application to run successfully, http://127.0.0.1:8888/HelloWorldService/metadata enter this address in your browser, you will get the service metadata as shown below.

  When you run the host application, if you do not run the host application with administrator privileges, you will be unable to register Http abnormal, the specific exception information as shown below:

  At this point, if you are running a host program in VS, you will need to run with administrator privileges VS2012, if the host running the program directly in the folder, then need right host program exe file, select Run as Administrator on abnormal shown above does not occur. MSDN detailed explanation of connection: WCF Formentera troubleshooting tutorial.

  And during the real WCF application development, it will not be defined and added service endpoint behavior directly through hard-coded, but rather by way of the configuration file. You can by way of the following configuration files instead of hard-coding the above.

<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8888/HelloWorldService/metadata"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="metadataBehavior" name ="Services.HelloWorldService">
<endpoint address="http://127.0.0.1:8888/HelloWorldService"
binding="wsHttpBinding"
contract="Contract.IHelloWorld"/>
</service>
</services>
</system.serviceModel>
</configuration>

步骤三:创建客户端

  服务成功寄宿之后,服务端便开始了服务调用请求的监听工作。另外,服务寄宿将服务描述通过元数据的方式发布出来,相应的客户端就可以获取这些元数据来创建客户端程序来对服务进行调用。在Visual Studio下,当我们添加服务引用时,VS在内部会帮我们实现元数据的获取,并通过代码生成工具(SvcUtil.exe)将这些元数据自动生成用于服务调用的服务代理相关的代码和相应的配置。  

  在成功运行服务寄宿程序后,右键客户端项目,在弹出的菜单中选择“添加服务引用”,然后在弹出的添加服务引用窗口中输入服务元数据的地址:http://127.0.0.1:8888/HelloWorldService/metadata,并指定一个命名空间,点击确定按钮(具体效果如下图所示),VS将为你生成用于服务调用的代理类代码和配置信息。

  添加成功之后,我们可以通过创建服务代理类对象来对服务相应方法进行调用操作,客户端进行服务调用的具体实现代码如下所示:

1 using Client.HelloWorldServices;
2 using System;
3
4 namespace Client
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 // HelloworldServiceClient就是VS为我们创建的服务代理类
11 using (HellworldServiceClient proxy = new HellworldServiceClient())
12 {
13 // 通过代理类来调用进行服务方法的访问
14 Console.WriteLine("服务返回的结果是: {0}", proxy.GetHelloWorld());
15 }
16
17 Console.Read();
18 }
19 }
20 }

  运行客户端程序后,你将获得如下图所示的运行结果。

  上面演示了通过自我寄宿的方式来寄宿服务,接下来我们来演示如何将WCF服务寄宿到IIS中。因为WCF服务和服务契约在上面方式中已实现,所以IIS寄宿方式的包含两个步骤:创建IIS宿主服务和创建客户端调用程序。下面分别介绍下这两个步骤。

步骤一:创建IIS宿主服务

  在开始的解决方案中,创建一个Asp.net空Web应用程序,然后添加一个WCF服务文件。这里WCF服务文件与Web 服务中的.asmx文件类似。基于IIS的服务寄宿要求相应的WCF服务具有相应的.svc文件,.svc文件部署于IIS站点中,对WCF服务的调用体现在对.svc文件的访问上。

 WCF服务文件的内容很简单,仅仅包含一个ServiceHost指令,该指令具有一个必须的Service属性和一些可选的属性。详细信息见MSDN:@ServiceHost。所以对应的.svc文件内容如下所示:

<%@ ServiceHost Language="C#" Debug="true" Service="Services.HelloWorldService" %>

具体Web.Config的配置内容如下所示:

<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="metadataBehavior" name ="Services.HelloWorldService">
<endpoint binding="wsHttpBinding"
contract="Contract.IHelloWorld"/>
</service>
</services>
</system.serviceModel>
</configuration>

  从上面配置内容可以看出,这基本上和自我寄宿方式的配置文件一致,唯一不同的是在添加终结点中无需指定地址,因为.svc所在的地址就是服务的地址。

步骤二:创建客户端程序

  此时,客户端仅仅需要修改终结点地址来对寄宿于IIS下的HellworldService进行访问,该地址为:http://localhost:15826/HelloWorldService.svc。此时可以http://localhost:15826/HelloWorldService.svc?wsdl得到相应的元数据。具体客户端代码的实现如下所示:

1 using Client2.HelloWorldService;
2 using System;
3
4 namespace Client2
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 using (HellworldServiceClient proxy = new HellworldServiceClient())
11 {
12 Console.WriteLine("服务返回的结果是: {0}", proxy.GetHelloWorld());
13 }
14
15 Console.Read();
16 }
17 }
18 }

  具体的配置文件内容如下所示:

<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_HellworldService" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:15826/HelloWorldService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_HellworldService"
contract="HelloWorldService.HellworldService" name="WSHttpBinding_HellworldService">
</endpoint>
</client>
</system.serviceModel>
</configuration>

  运行客户端2,得到的运行结果与自我寄宿方式得到的结果一样。这里就不贴出结果图了。

四、总结

  到这里,本篇文章的分享就结束。本文首先通过介绍WCF相关的基础概念,其中最重要的莫过于终结点和组成它的三个元素,之后分别介绍自我寄宿和IIS寄宿方式来创建WCF应用程序,在平常开发过程中,用到最多是通过IIS寄宿方式来对服务进行寄宿。前面的关于WCF的知识点大家可以翻阅历史记录学习哦~

 

转自:https://www.cnblogs.com/zhili/p/MSMQ.html,作者:Learning hard。

如有侵权,请联系我删除!

Guess you like

Origin blog.csdn.net/IT_0802/article/details/91501175