Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop Windows Communication Interface in WCF

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "how to develop Windows communication interface in WCF". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Overview

WCF:Windows Communication Foundation, Windows communication foundation.

SOP:Service Orientation Architechture, a service-oriented architecture.

WebService is a WCF that runs as BasicHttpBing.

Programme structure:

1. Create a solution WCFService

Add four items in turn, such as the figure above, Client and Hosting are console applications, and Service and Service.Interface are class libraries.

2. Citation relationship

Service.Interface: defines the service contract (Service Contract) interface, referencing the WCF core library System.ServiceModel.dll

Service: the project that defines the service. Because the specific service needs to be implemented and the service contract is in Service.Interface, the Service.Interface project should be referenced.

Hosting: the console program of the service host, which needs to reference the Service.Interface and Service projects, as well as the System.ServiceModel.dll class library:

Client: a client of a console application that needs to reference the Service.ServiceModel class library.

I. Contracts Agreement

A class library project that defines a service contract.

The service contract abstracts all the operations of the service, and the general contract exists in the form of interface.

/ / Service agreement [ServiceContract (Name = "ICalculator", Namespace = "portType namespace for http://SampleWcfTest")] / / webservice description file / / CallbackContract = typeof (ICallBack), / / return agreement / / ConfigurationName =" Calculator "for duplex, / / service name / / ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign for configuration file) / / Protection level / / SessionMode = support mode for SessionMode.Allowed// setup session public interface ICalculator {/ / Operation Agreement [OperationContract] double Add (double N1, double N2) } II. Services service

A class library project that provides the implementation of contracts.

Public class Calculator: ICalculator {public double Add (double N1, double N2) {double result = N1 + N2; Console.WriteLine ("Received Add ({0}, {1})", N1, N2); / / Code added to write output to the console window. Console.WriteLine ("Return: {0}", result); return result;}

The WCF Service Library Project of VS automatically generates the svc file, the corresponding svc.cs file and the App.config file. Running this project will automatically launch the WCF Service Host and WCF Test client window.

III. ServiceHost self-service host

A console project that hosts Sevice project services through self-hosting. The hosting process is ServiceHost1.exe.

The purpose of service hosting is to start a process, provide a running environment for the WCF service, add one or more endpoints to the service, and then leak it to the service consumer.

A WCF service needs a running hosting process, and service hosting is the process of assigning a host to the service. 、

Endpoint (EndPoint)

WCF adopts the means of communication based on endpoint (EndPoint). The endpoint consists of three parts: address (Address), Binding (binding) and Contract (contract). The three elements can also be recorded as EndPoint=ABC.

An endpoint contains all the information necessary for communication, as follows:

Address: address determines the location of the service and solves the addressing problem

Binding: binding implements all the details of communication, including network transport, message encoding, and other corresponding processing of messages for certain functions (such as transport security, reliable message transmission, transactions, etc.).

There are a series of system-defined bindings in WCF, such as BasicHttpBinding,WSHttpBinding and NetTcpBinding,WSHttpBinding, NetMsmqBindiing, etc.

Contract: a contract is an abstraction of service operations and a definition of message exchange patterns and message structures.

1. Encoding method / / Host using of the service (ServiceHost selfHost = new ServiceHost (typeof (Calculator) {try {/ / add service endpoint selfHost.AddServiceEndpoint (typeof (ICalculator), new WSHttpBinding (), new Uri ("http://localhost:8000/GettingStarted/"));) / / add service metadata behavior if (selfHost.Description.Behaviors.Find () = = null) {ServiceMetadataBehavior smb = new ServiceMetadataBehavior (); smb.HttpGetEnabled = true; smb.HttpGetUrl = new Uri ("http://localhost:8000/GettingStarted/metadata") selfHost.Description.Behaviors.Add (smb);} selfHost.Open () Console.WriteLine ("The service is ready."); Console.WriteLine ("input to terminate service."); Console.WriteLine (); while ("exit" = = Console.ReadLine ()) {selfHost.Close ();}} catch (CommunicationException ex) {Console.WriteLine (ex.Message); selfHost.Abort ();}} 2, configuration file method

Open app.config in the Hosting project and add the following code.

You can directly right-click the config file and choose "Edit WCF configuration" menu, or through the VS "tools" menu, choose "WCF Service configuration Editor" menu to edit the configuration file.

Service behavior

The Hosting code is modified as follows:

Using (ServiceHost host = new ServiceHost (typeof (CalculatorService) {host.Opened + = delegate {Console.Write ("CalculatorService has been started, press any key to terminate the service");}; host.Open (); Console.Read ();} IV, IIS host

A Web application that hosts services in IIS through IIS hosting

The hosting process is w3wp.exe. WAS Activation Service: Window Activation Services.

1. Create a WCF service file: CalculatorService.svc:

2. Configuration file

Compared with app.config, web.config has no EndPointAddress? The address of the service is the address of .svc, and the default metadata is … .. / CalculatorService.svc?ws...

Fifth, implement Rest-style web services

You can use the WCF REST programming model.

Default WebHttpBinding.

Add WebGet or WebInvoke attributes to the implementation of the contract

[OperationContract] [WebInvoke (UriTemplate = "div?x= {x} & y = {y}")] long Divide (long x, long y); [OperationContract] [WebGet (UriTemplate = "hello?name= {name}")] string SayHello (string name)

Example 2:

[ServiceContract] public interface ITestService {[OperationContract] [WebInvoke (Method = "POST", UriTemplate = "Test1", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] string Test1 (string userName, string password); [OperationContract] [WebGet (UriTemplate = "Test/ {id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] string Test (string id);} VI. Use the preconfigured host class WebServiceHost

Use the WebServiceHost class

Uri baseAddress = new Uri ("http://localhost:8000/");WebServiceHost svcHost = new WebServiceHost (typeof (CalcService), baseAddress); try {svcHost.Open (); Console.WriteLine (" Service is running "); Console.WriteLine (" Press enter to quit... "); Console.ReadLine (); svcHost.Close ();} catch (CommunicationException cex) {Console.WriteLine (" An exception occurred: {0} ", cex.Message); svcHost.Abort ();}

3. Call:

Http://... / div?x=1&y=2

7. Client: a client 1. CalculatorServiceClient generated using VS "add service reference"

The CalculatorServiceClient base class is System.ServiceModel.ClientBase, which encapsulates ChannelFactory

Using (CalculatorServiceClient proxy = new CalculatorServiceClient ()) {double result = proxy.Add (1,2); Console.WriteLine ("Add ({0}, {1}) = {2}", value1, value2, result) 2. Instead of adding service references, use ChannelFactory method / / using (ChannelFactory channelFactory = new ChannelFactory (new WSHttpBinding ()), "ABC three elements of the endpoint specified in the http://127.0.0.1:1111/CalculatorService"))// constructor, using (ChannelFactory channelFactory = new ChannelFactory (" CalculatorService ")) / / through the configuration file, corresponding to the name {ICalculator proxy = channelFactory.CreateChannel () of the endpoint in the config file. Using (proxy as IDisposale) {Console.WriteLine ("xylene = {2} when x = {0} and y = {1}", 1,2, proxy.Add (1,2));}}

Configuration file:

8. Binding type

Binding methods commonly used in WCF:

1. Binding based on HTTP

The BasicHttpBinding, WSHttpBinding, WSDualHttpBinding, and WSFederationHttpBinding options are suitable for providing contract types through XML Web service agreements. Obviously, if you need to make the service available in more situations (multiple operating systems and multiple programming languages), these are bindings of concern, because all of these binding types are based on the XML representation of encoded data and use HTTP to transfer the data.

In the following listing, notice that WCF bindings can be represented in code (through class types in the System.ServiceModel namespace), or as XML attributes defined in the * .config file to represent WCF bindings.

BasicHttpBinding: used to bind WCF services that conform to WS-Basic Profile (WS-I Basic Profile 1.1). The binding uses HTTP as the delivery method and Text/XML as the default message encoding. Used to be compatible with older Web ASMX services.

BasicHttpBinding is the simplest of all Web service-centric protocols. In particular, the binding will ensure that the WCF service conforms to the specification called WS-I Basic Profile 1.1 defined by WS-I.

WSHttpBinding: similar to BasicHttpBinding, but provides more Web service features. This binding adds support for transactions, reliable messaging, and WS-Addressing.

The WSHttpBinding protocol not only integrates support for a subset of the WS-* specification (transaction, security, and reliable session), but also supports the ability to handle binary data encoding using the message Transport Optimization Mechanism (Message Transmission Optimization Mechanism,MTOM).

WSDualHttpBinding: similar to WSHttpBinding, but used in conjunction with a two-way contract (for example, services and customers can send messages back and forth). This binding only supports SOAP security and requires reliable message delivery.

The main advantage of WSDualHttpBinding is that it adds the ability to allow callers and senders to communicate using two-way messaging (duplex messaging), a popular way to indicate that callers and senders can participate in two-way talks. When you select WSDualHttpBinding, you can associate it with the WCF publish / subscribe event model.

WSFederationHttpBinding: secure and interoperable binding that supports the WS-Federation protocol and allows organizations within the federation to effectively authenticate and authorize users

WSFederationHttpBinding is a protocol based on Web services, which is needed when security is most important. The binding supports the WS-Trust, WS-Security, and WS-SecureConversation specifications, which are represented by WCF CardSpace API.

WebHttpBinding: useful for service queue script clients that are provided through HTTP (non-SOAP) requests, such as ASPNet AJAX.

two。 Binding based on TCP

If you are building a distributed system that involves a set of networked machines configured with the .NET 3.0 Windows Server 3.5 library (in other words, all machines are running Windows XP, Windows Server 2003, or Windows Vista), you can enhance performance by bypassing the Web service binding and choosing to use the TCP binding, which ensures that all data is encoded in a compact binary format (rather than XML). Similarly, when using the bindings in the following table, the client and host must be .NET applications.

NetNamedPipeBinding: secure, reliable, optimized binding for communication between different .NET applications on the same machine.

NetNamedPipeBinding supports transactions, reliable sessions, and secure communication, but it cannot perform calls across machines. If you are looking for the fastest way to promote data (for example, communication across the application's domain) between WCF applications on the same machine, NetNamedPipeBinding binding is the best choice.

NetPeerTcpBinding: provides secure binding for peer-to-peer (P2P) network applications.

As for NetPeerTcpBinding, check the .NET Framework 3.5 SDK documentation for details on P2P networking.

NetTcpBinding: secure, optimized bindings for communication between .NET applications on different machines.

The NetTcpBinding class uses TCP to move binary data between the customer and the WCF service. As mentioned earlier, this will result in better performance than Web service protocols, but only for internal application solutions. In addition, NetTcpBinding supports transactions, reliable sessions, and secure communication.

3. Binding based on MSMQ

MsmqIntegrationBinding: this binding can be used to allow WCF applications to send and receive messages to and from existing MSMQ applications that use COM, native C++, or types defined in the System.Messaging namespace

NetMsmqBinding: this queued binding is suitable for communication between .NET applications on different machines

Note: the binary encoding format uses TCP, IPC, and MSMQ to get the best performance, but it is at the expense of interoperability because it only supports WCF-to-WCF communication.

This is the end of the content of "how to develop Windows communication interface in WCF". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report