[WCF programming] 1. Example of getting started with WCF, and example of wcf programming 1. Example of wcf
I. What is WCF?
Windows Communication Foundation (WCF) is a series of application frameworks developed by Microsoft to support data Communication. It integrates the original windows Communication. net Remoting, WebService, Socket mechanism, and integration with Http and Ftp technologies are the best practices for developing distributed applications on Windows platforms. With this framework, developers can build cross-platform, secure, reliable, and enterprise-level interconnected application solutions that support transaction processing.
Ii. Benefits of WCF
1. Uniformity
WCF covers all the technologies that Microsoft has released for distributed development, including Remoting, Web Services, WSE, and MSMQ, and is implemented in a unified programming mode.
2. Interoperability
The most basic communication mechanism of WCF is SOAP (Simple Object Access Protocol), which ensures the interoperability between systems and can also be implemented.. NET client and.. NET Server Communication, providing support for distributed transactions.
3. Security and Reliability
In terms of security, WCF fully complies with the WS-* standard, and adds WS-ReliableMessaging to the soap header to allow trusted end-to-end communication. The SOAP-based information exchange based on WS-Coordination and WS-AtomicTransaction supports two-phase commit transactions ).
4. Compatibility
WCF fully considers compatibility with old systems. Installing WCF does not affect existing technologies such as ASMX and. Net Remoting. Even though both of them use SOAP, applications developed based on WCF can still directly interact with ASMX.
Features |
Web Service |
. NET Remoting |
Enterprise Services |
WSE |
MSMQ |
WCF |
Web services with interoperability |
Supported |
|
|
|
|
Supported |
. NET to. NET Communication |
|
Supported |
|
|
|
Supported |
Distributed transactions |
|
|
Supported |
|
|
Supported |
WS standards supported |
|
|
|
Supported |
|
Supported |
Message Queue |
|
|
|
|
Supported |
Supported |
Iii. Simple WCF example
1. Establish a solution
WCF. Host must reference WCF. Service, and WCF. HostByWeb must reference WCF. Service.
2. WCF. Service Project:
IHelloWorldService. cs file:
[ServiceContract(Namespace="www.cnblogs.com")] public interface IHelloWorldService { [OperationContract] string SayHello(string str); [OperationContract] Student Say(); } [DataContract] public class Student { [DataMember] public string UserName { get; set; } [DataMember] public int Age { get; set; } [DataMember] public GenderMode Gender { get; set; } } public enum GenderMode { Man = 1, Woman = 2, UnKnown = 3 }
HelloWorldService.cs
Public class HelloWorldService: IHelloWorldService {public string SayHello (string str) {return "you said:" + str;} public Student Say () {Student stu = new Student () {UserName = "zxj", Age = 20, Gender = GenderMode. man}; return stu ;}}
3. WCF. Host (using console programs as the Host)
1. Configure the endpoint as a configuration file
Program. cs File
Class Program {static void Main (string [] args) {ServiceHost host = new ServiceHost (typeof (WCF. service. helloWorldService); Console. foregroundColor = ConsoleColor. darkYellow; host. open (); Console. writeLine ("service started successfully ...... "); int I = 0; foreach (ServiceEndpoint endpoint in host. description. endpoints) {I ++; Console. writeLine ("endpoint No.: {0}, endpoint name: {1}, endpoint address: {2}, end point binding: {3} {4 }", i, endpoint. name, endpoint. address, endpoint. binding, Environment. newLine);} Console. read ();}}
App. config file
<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <startup> <supportedRuntime version = "v4.0" sku = ". NETFramework, Version = v4.5 "/> </startup> <system. serviceModel> <services> <service name = "WCF. service. helloWorldService "> <endpoint address =" http://localhost:8000 /HelloWorldService "contract =" WCF. service. IHelloWorldService "binding =" wsHttpBinding "> </endpoint> <endpoint address =" mex "binding =" mexHttpBinding "contract =" IMetadataExchange "> </endpoint>
2. Configure endpoints programmatically
Class Program {static void Main (string [] args) {// configure the endpoint Uri baseAddress = new Uri (" http://localhost:8000 "); ServiceHost host = new ServiceHost (typeof (WCF. service. helloWorldService), baseAddress); WSHttpBinding binding = new WSHttpBinding (); // search for metadata ServiceMetadataBehavior metadataBehavior = host. description. behaviors. find <ServiceMetadataBehavior> (); // obtain the behavior list of the host if (metadataBehavior = null) // if there is no behavior for the Service's original data exchange, instantiate and add the original service data exchange behavior {metadataBehavior = new ServiceMetadataBehavior (); metadataBehavior. httpGetEnabled = true; host. description. behaviors. add (metadataBehavior);} host. addServiceEndpoint (typeof (WCF. service. IHelloWorldService), binding, "HelloWorldService"); host. addServiceEndpoint (typeof (IMetadataExchange), binding, "mex"); Console. foregroundColor = ConsoleColor. darkYellow; host. open (); Console. writeLine ("service started successfully ...... "); int I = 0; foreach (ServiceEndpoint endpoint in host. description. endpoints) {I ++; Console. writeLine ("endpoint No.: {0}, endpoint name: {1}, endpoint address: {2}, end point binding: {3} {4 }", i, endpoint. name, endpoint. address, endpoint. binding, Environment. newLine);} Console. read ();}}
4. For WCF. Client (Client, console Program), you need to add System. Runtime. Serialization and System. ServiceModel references.
Use svcutil.exe to generate the server proxy class. The usage is as follows:
Visual Studio --> menu bar --> Tools --> external tools
Start the Host Program, It is best to useRight-click an administratorOpen the console Host Program
After the main program starts, open the svcutil.exe program,
Visual Studio --> menu bar --> tool --> svcutil(this is the title of svcutil.exe when the external tool is configured in the previous step)
Enter the metadata address of the host:
Click OK,
If you select the same configuration as me When configuring external tools, you can find HelloWorldService in the solution root directory. in the cs and output configuration files, set HelloWorldService. cs is directly copied to WCF. in the Client project, open the output configuration file and copy the content to the WCF. app in Client project. config configuration file
Program. cs
Class Program {static void Main (string [] args) {HelloWorldServiceClient client = new HelloWorldServiceClient (); string temp = client. SayHello ("Hello! "); Console. writeLine (temp); Student stu = client. say (); Console. writeLine ("username:" + stu. userName + ", age:" + stu. age + ", Gender:" + stu. gender); Console. read ();}}
Generate a solution. First run the host console application and then the client console program. The client console program results are shown in:
At this point, the host-based example of the console application has been completed. The following describes an example of a Web application-based HOST:
5. WCF. HostByWeb (host, Web program)
Create a "WCF Service Application ",:
Add reference to the WCF. Service Project, delete IService1.cs, IService1.svc, and create the WebHelloWorldService. svc page.
Delete the IWebHelloWorldService. cs and WebHelloWorldService. svc. cs files,
Open WebHelloWorldService. svc:
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService2.WebHelloWorldService" CodeBehind="WebHelloWorldService.svc.cs" %>
To:
<%@ ServiceHost Language="C#" Debug="true" Service="WCF.Service.HelloWorldService" %>
Mainly Service = "WCF. Service. HelloWorldService ".
Right-click WebHelloWorldService. svc and browse in the browser:
In this case, the url I obtained is: http: // localhost: 32797/WebHelloWorldService. svc.
6. For the WCF. ClientByWeb Project (client, console Program), you must add System. Runtime. Serialization and System. ServiceModel references.
In this example, we also use the svcutil.exe tool to generate the corresponding data based on the URL address. You can directly refer to step 1.
Note: This sample code is for reference only and cannot be used for actual development.
Download source file: wcf1_ .rar
Programming example of popular issues in WCF (1): How does the WCF Service obtain client address information?
// Call the SayHelloToUser service by proxy
StrMessage = wcfServiceProxyHttp. SayHelloToUser (strUserName );
Console. WriteLine (strMessage );
}
// 2. NetTcpBinding_IWCFService
Using (WCFServiceClient wcfServiceProxyHttp = new WCFServiceClient (WSHttpBinding_IWCFService ))
{
String strUserName = Frank Xu Lei NetTcpBinding;
String strMessage =;
// Call the SayHelloToUser service by proxy
StrMessage = wcfServiceProxyHttp. SayHelloToUser (strUserName );
Console. WriteLine (strMessage );
}
// 3. BasicHttpBinding_IWCFService
Using (WCFServiceClient wcfServiceProxyHttp = new WCFServiceClient (WSHttpBinding_IWCFService ))
{
String strUserName = Frank Xu Lei BasicHttpBinding;
String strMessage =;
// Call the SayHelloToUser service by proxy
StrMessage = wcfServiceProxyHttp. SayHelloToUser (strUserName );
Console. WriteLine (strMessage );
}
// 4. WSDualHttpBinding_IWCFService,
Using (WCFServiceClient wcfServiceProxyHttp = new WCFServiceClient (WSHttpBinding_IWCFService ))
{
The classic tutorial for getting started with WCF is now a newbie. I want to learn something about it.
Microsoft's examples are available from entry-level to master-level.