Learn WCF with me (3) -- use Web Services to develop distributed applications, wcfservices

Source: Internet
Author: User
Tags msmq

Learn WCF with me (3) -- use Web Services to develop distributed applications, wcfservices
I. Introduction

The MSMQ and. NET Remoting technologies are introduced in the previous article. Today, we will continue to share another distributed technology, Web Services, on the. NET platform.

Ii. Web Services details 2.1 Overview of Web Services

Web Services is a software system that supports network interoperability between clients and servers. It is a group of application program APIs that can be called over the network. In Web Services, the three core concepts SOAP/UDDI/WSDL are introduced. The definitions of these three concepts are described below.

  • SOAP: SOAP (Simple Object Access Protocol) is a Simple Protocol for exchanging information in a distributed or distributed environment. It is an XML-based Protocol, you need to bind a network transmission protocol to complete information transmission. This protocol is usually Http or Https, but other protocols can also be used.

It consists of four parts:

SOAP encapsulation: it defines a framework that describes the content in a message, who sends the message and who should receive and process it;

SOAP encoding rules: defines a serialization mechanism to represent instances of the data types required by applications;

Soap rpc: indicates a protocol used to indicate remote process calls and responses;

SOAP binding: it defines the protocol used by SOAP for information exchange. Http, TCP, and UDP can all be used. It is consistent with the concept of binding in WCF.

In other words, the SOAP protocol is only used to encapsulate messages. You can transmit encapsulated messages through various existing protocols, such as Http, Https, Tcp, UDP, and SMTP, you can even customize the protocol. However, Web services use Http to transmit data. For more information about How to Use Https to access Web Services, see how to use SSL to call Web Services.

  • UDDI: the abbreviation of Universal Description, Discovery, and Integration. It is a cross-platform Description specification based on XML, enterprises around the world can publish their own services on the Internet for query and use by other customers.
  • WSDL: Web Service Description Language (WSDL), which is an XML format used to describe the Web Service Release. It is used to describe the details of the server port access method and the protocol used to assist the production server and client code and configuration information.

 

2.2 Web Services implementation process

The implementation process of calling Web Services is similar to that of calling conventional methods. The difference is that the former method is not located in the client application, but is used to generate request messages through the specified transmission protocol. Because Web Services may be deployed on different computers, the information required by Web Services to process requests must be transmitted to the server containing Web Services over the network. After processing information, the results are sent back to the client application over the network. Shows the communication process between the client and Web Services:


The following describes the sequence of events that occur when Web Services is called:

2.3 Advantages and Disadvantages of Web Services

After detailed introduction, Web Services has the following advantages:

  • Cross-platform: Web Services are fully based on industry standards unrelated to the platform, such as XML (Extensible Markup Language) and XSD (XMLSchema.
  • Self-description: Web Service uses WSDL for self-description, including related information such as Service methods, parameters, types, and return values.
  • Cross-firewall: Web services use http to communicate with each other and can pass through the firewall.

Web Services also has the following Disadvantages:

  • Inefficient, not suitable for single application system development.
  • Security Problem: Web Services does not have its own security mechanism. It must implement information security encryption through host programs such as Http protocol or IIS.
3. Use Web Services to develop distributed applications

Using Web Services to develop distributed applications is much simpler than MSMQ and. NET Remoting. Today's sample programs take three steps:

1 namespace WebServiceUserValidation
2 {
3     public class UserValidation
4 {
5 / / judge whether the user name and password are valid
6         public static bool IsUserLegal(string name, string psw)
7 {
8 / / users can access the database for user and password authentication
9 / / this is just a demonstration
10             string password = "LearningHard";
11             if (string.Equals(password, psw))
12             {
13                 return true;
14             }
15             else
16             {
17                 return false;
18             }
19}
Twenty
21 / / judge whether the user's credentials are valid
22         public static bool IsUserLegal(string token)
23 {
24 / / users can access the database to verify their credentials
25 / / only for demonstration
26             string password = "LearningHard";
27             if (string.Equals(password, token))
28             {
29                 return true;
30             }
31             else
32             {
33                 return false;
34             }
35}
36}
37}

2. To create a Web Services Service class, you must create a message inherited from the SoapHeader to receive messages in the SOAP header and add the WebServiceUserValidation assembly. Create a Web Services Service Project by adding an Asp.net empty Web application, right-click the created Web application project, and add a Web service file to create a Web service. The specific implementation code is as follows:

1 / / user defined soapheader class must inherit from soapheader
2     public class MySoapHeader : SoapHeader
3 {
4 / / store user credentials
5         public string Token { get; set; }
6}
7  /// <summary>
8 / / / summary description of learninghardwebservice
9     /// </summary>
10     [WebService(Namespace = "http://www.cnblogs.com/zhili/")]
11     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12     [System.ComponentModel.ToolboxItem(false)]
13 / / if you want to allow the use of ASP.NET AJAX to invoke the Web service from the script, cancel the following lines.
14     // [System.Web.Script.Services.ScriptService]
15     public class LearningHardWebService : System.Web.Services.WebService
16 {
17 / / store the soap header information of user credentials
18 / / the public and field names must be the same as the membername in soapheader ("membername")
19 / / otherwise, "the header property / field LearningHardWebService.authenticationToken is missing or not public." Anomaly
20         public MySoapHeader authenticationToken;
21 private const string token = "LearningHard"; / / store server-side credentials
Twenty-two
Twenty-three
24 / / define the direction of soapheader delivery
25 / / soapheaderdirection.in; only send soapheader to server, which is the default value
26 / / soapheaderdirection.out; send soapheader to client only
27 / / soapheaderdirection.inout; send soapheader to server and client
28 / / soapheaderdirection.fault; if the server method is abnormal, the exception information will be sent to the client
29         [SoapHeader("authenticationToken", Direction = SoapHeaderDirection.InOut)]
30         [WebMethod(EnableSession = false)]
31         public string HelloLearningHard()
32 {
33             if (authenticationToken != null &amp;&amp; UserValidation.IsUserLegal(authenticationToken.Token))
34             {
35 return "LearningHard, call service method succeeded!";
36             }
37             else
38             {
39 throw new soapexception ("authentication failed", soapexception. Serverfaultcode);
40             }
41}
42}

In the above Code, it should be noted that the Web method in Web Servies must throw a SoapExcetion exception before it can be captured by the client. If the Debug mode is used for debugging, you also need to check this exception in the exception settings, that is, the compiler does not capture this exception.

3. create a console client and add Web Services by adding service references. After successful addition, a proxy class is created in the client program. The client can call the Web Services method through the proxy class, the specific implementation code is as follows:

1 namespace WebServiceClient
2 {
3     class Program
4 {
5         static void Main(string[] args)
6 {
7 / / instantiate a soap protocol header
8             MySoapHeader mySoapHeader = new MySoapHeader() { Token = "LearningHard"};
9             string sResult = string.Empty;
10             LearningHardWebServiceSoapClient learningHardWebSer = null;
11             try
12             {
13 / / instantiate the client proxy class of the web service
14                 learningHardWebSer = new LearningHardWebServiceSoapClient();
15 / / call method on Web Service
16                 sResult= learningHardWebSer.HelloLearningHard(ref mySoapHeader);
17 / / output results
18                 Console.WriteLine(sResult);
19             }
20             catch
21             {
22 console. Writeline ("failed to call web service!");
23             }
24             finally
25             {
26 / / release managed resources
27                 if (learningHardWebSer != null)
28                 {
29                     learningHardWebSer.Close();
30                 }
31             }
Thirty-two
33 console. Writeline ("please press any key to end...");
34             Console.ReadLine();
35}
36}
37}

For more information about Web Services exception capture, see MSDN: process and cause exceptions in XML Web services. However, the sample code on MSDN seems to be unsuccessful. Later, we found that the client in this article only processes the SoapException exception, and the FaultException exception occurs when the client triggers the exception, so the Exception handling code should be handled like the following code. Of course, you can only handle Exception exceptions directly. The above Code only handles this large range of exceptions.

catch (SoapException ex)
    {
        // Do sth with SoapException 
    }
    catch (Exception ex)
    {
        // Do sth with Exception
    }

After the above steps, we have completed all the development work. Run the following to test the running effect of the program. Use WebServiceClient as the startup project and press F5 or Ctrl + F5 to run the client program. You will see the following results:


Note: For distributed applications, the application first runs the server and then the client to access the service method. Here, we can directly run the client to access the Web methods in Web Services. This is because before running the Web Services Client program, you will first deploy Web Services to IIS Express. You will see the right-click the icon in the lower right corner of the taskbar to see the running Web Services.

Iv. Summary

Here, the sharing of Web Services technology is over. Starting from the next article, it will officially enter the world of WCF. The content of Web Services is the same as that of WCF, but Microsoft officially recommends using WCF to create Web service programs. If you want to learn more about Web Services, refer to MSDN: use ASP. XML Web Services and XML Web Services Client created by. NET

Download all the sample code in this article: WebServiceSample

 


Which of the following is the high efficiency of webservice and WCF?

Comparing web Services and wcf, there are a lot of online services. It is better to connect the client to the server using wcf because it can be abstracted as soa and you can adopt the esb approach. This is what our mes product is like!
If it is a small project, you can directly connect to the database. However, this is not safe. All the database items are exposed, and web services cannot be used to push services, however, using wcf is different. The other two are similar. They are all about the soap protocol.

The wcf Service Application is different from the aspnet web application.

The wcf Service Application in VS is actually the asp.net web that can publish the service. The web site here is actually the Host Program of the Service released by wcf. Of course, this host program is not necessarily web, but also windows application. That is to say, the wcf Service can be published on IIS or windows server.

Wcf is a feature of a service that is released for remote cross-platform calling. It can be released through http, tcp, message queue, and other methods for remote cross-platform calling and access.

You are right about adding a WCF Service or AJAX-enabled WCF Service file on the web site and releasing the service for remote call, this web project is the host of the wcf Service. You must start this web project to remotely access the published wcf Service.

Finally, we recommend that you check webservice and. net remoting. The cross-platform communication methods are finally integrated into wcf.

Related Article

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.