WCF simple tutorial (1) getting started

Source: Internet
Author: User

WCF is a very important technology in the DotNet system. However, many team members in the group feel that they are too broad, the configuration files are too complex, and there are too many new terms and cannot grasp the clues, I decided to conduct a group technical training and sort out the training handouts on the blog. It is not a big but comprehensive solution, but a quick start for beginners. Therefore, we want to start with an instance and deliberately hide some content that is not available at the beginning to lower the entry threshold. Please correct me if you have any errors.

Note: this series of articles is Based on. Net Framework 3.5. At the end of the tutorial, We will summarize the differences in 4.0.

----------------------- Separation line -----------------------

Article 1: getting started, build the first WCF Program

1. Server

Create a console application as the Server and create an API IData as the service contract. This contract interface must be placed on the Client side in a short time so that both parties can follow the same standards. Do not forget to add a reference to System. ServiceModel.

 
 
  1. Using System;

  2. Using System. ServiceModel;

  3. Using System. Text;

  4. Namespace Server

  5. {

  6. /// <Summary>

  7. /// ServiceContract is used to mark this interface as a service contract of WCF, you can specify a Namespace like WebService, if not specified, is the default http://tempuri.org

  8. /// </Summary>

  9. [ServiceContract (Namespace = "WCF. Demo")]

  10. Public interface IData

  11. {

  12. /// <Summary>

  13. /// Use OperationContract to mark this method as an operation contract

  14. /// </Summary>

  15. [OperationContract]

  16. String SayHello (string userName );

  17. }

  18. }


To create an implementation class for this interface, this class actually works. It works on the server and does not appear on the client:

 
 
  1. Using System;

  2. Using System. Text;

  3. Namespace Server

  4. {

  5. /// <Summary>

  6. /// Implement the IData interface. No contract mark is required here.

  7. /// </Summary>

  8. Public class DataProvider: IData

  9. {

  10. Public string SayHello (string userName)

  11. {

  12. Return string. Format ("Hello {0}.", userName );

  13. }

  14. }

  15. }


Add an App. config file for the project, which defines parameters related to service release. In WCF, a common practice is to write Service Logic using code, but to define the service publishing method using configuration files, the advantage of this is loose coupling.

 
 
  1. <? Xmlversion = "1.0" encoding = "UTF-8"?>

  2. <Configuration>

  3. <System. serviceModel>

  4. <! -- When you see the services Section, it indicates that this is the definition of service-related content -->

  5. <Services>

  6. <! -- Define a service, and name is the full name of the contract implementation class -->

  7. <Servicename = "Server. DataProvider">

  8. <! -- To provide external services, you must have a service address, which is defined as http: // localhost: 8080/wcf. Note that the address always carries a type header. -->

  9. <Host>

  10. <BaseAddresses>

  11. <AddbaseAddress = "http: // localhost: 8080/wcf"/>

  12. </BaseAddresses>

  13. </Host>

  14. <! -- Defines the final node. The address is generally empty. If it is not empty, the final service address is added based on baseAddress, and the binding is specified as basicHttpBinding, this is the most basic http-based binding method, and contract indicates which contract service this is for -->

  15. <Endpointaddress = "" binding = "basicHttpBinding" contract = "Server. IData"/>

  16. </Service>

  17. </Services>

  18. </System. serviceModel>

  19. </Configuration>


Everything is ready, with only the last step left. Release the service:

 
 
  1. Using System;

  2. Using System. ServiceModel;

  3. Namespace Server

  4. {

  5. Class Program

  6. {

  7. Static void Main (string [] args)

  8. {

  9. // Define a ServiceHost. Note that the contract implementation class should be used in the parameter instead of the interface.

  10. Using (ServiceHost host = new ServiceHost (typeof (Server. DataProvider )))

  11. {

  12. Host. Open ();

  13. Console. WriteLine ("Service Running ...");

  14. Console. ReadKey ();

  15. Host. Close ();

  16. }

  17. }

  18. }

  19. }

Someone may ask where the service is released? No address specified? It is easy for beginners to understand.

Yes, the App. the definition in config plays a role, because the Server is specified in ServiceHost. dataProvider services, and App. name = "Server. the service of DataProvider has an endpoint, which defines the binding method as basicHttpBinding. The baseAddress of http is only one, that is, http: // localhost: 8080/wcf.

Compile and run the Service. The screen shows that the Service Running... is Running normally. If you use the command line netstat-ano | findstr "8080" to check whether the output is as follows:

 
 
  1. TCP    0.0.0.0:8080         0.0.0.0:0          LISTENING      4

  2. TCP    [::]:8080            [::]:0             LISTENING      4

It indicates that our program has started listening on TCP port 8080. It is worth noting that PID is 4, which is a system process rather than our own process. This indicates that the system function HTTP. sys is used when the WCF program provides http services externally ).

In this case, if you access http: // localhost: 8080/wcf in a browser, no error is reported, but the message "metadata publishing for this service is disabled" is displayed ", this is because http get is not allowed by default to obtain the Service's WSDL. We don't need to worry about it and it will not affect subsequent use. Let's look at this issue later.


2. Client

Create a console application as the Client and copy the IData interface in the Server, because this is a service contract.

Add an App to the project. in the config file, you need to define the client access parameters. Here I have removed some unused parameters to keep the configuration file simple and prevent you from getting dizzy.

 
 
  1. <? Xmlversion = "1.0" encoding = "UTF-8"?>

  2. <Configuration>

  3. <System. serviceModel>

  4. <! -- When you see the client, it indicates the client settings -->

  5. <Client>

  6. <! -- Define the End Node for access. The name is also random. Note that the address is the address of the baseAddress + endpoint specified when the Server is released, and the binding should also be matched. The contract should not be mentioned, because IData. the namespace is not modified when cs is copied, so it is still the Server. IData -->

  7. <Endpointname = "DataService" address = "http: /localhost: 8080/wcf" binding = "basicHttpBinding" contract = "Server. IData"/>

  8. </Client>

  9. </System. serviceModel>

  10. </Configuration>


Then write the code to call the SayHello method published by the Server:

 
 
  1. Using System;

  2. Using System. ServiceModel;

  3. Using System. ServiceModel. Channels;

  4. Namespace Client

  5. {

  6. Class Program

  7. {

  8. Static void Main (string [] args)

  9. {

  10. // There are multiple client access methods. Only one method is displayed here.

  11. // Use the CreateChannel method of ChannelFactory to create an IData proxy object. The parameter "DataService" is the name of the endpoint defined in App. config.

  12. Var proxy = new ChannelFactory <Server. IData> ("DataService"). CreateChannel ();

  13. // Call the SayHello Method

  14. Console. WriteLine (proxy. SayHello ("WCF "));

  15. // Be sure to close the connection after use, because the server has the maximum number of connections. If you do not close the connection, it will occupy valid connections for a certain period of time.

  16. (IChannel) proxy). Close ();

  17. }

  18. }

  19. }

Compile and run the program. The screen should be able to print "Hello WCF .". The first entry-level demo is completed. It should be relatively simple. The configuration of App. config is a little complicated. We will see later that you can do it without configuring it, but we do not recommend this from the perspective of loose coupling.


This article from the rabbit nest blog, please be sure to keep this source http://boytnt.blog.51cto.com/966121/796884

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.