WCF (3) the use of Web Services Distributed Application Development

I. Introduction

  In the previous article we introduced the MSMQ and .NET Remoting technology, today continue to share the .NET platform to another distributed technology --Web Services

Two, Web Services Detail

2.1 Web Services Overview

   Web Services is to support the client and server through a software system network interoperable API is a set of applications that can be invoked by the network. In the main Web Services to SOAP / UDDI / WSDL these three core concepts, the following were introduced under the definition of these three concepts.

  • SOAP: SOAP (Simple Object Access Protocol, Simple Object Access Protocol) is a decentralized or distributed environment to exchange information simple protocol, an XML-based protocol, need to bind a network transport protocol to complete the transfer of information, this agreement is usually Http or Https, but also can make other protocols.

  It consists of four parts:

  SOAP envelope: it defines a framework for describing what is described in the message, who sent the message, who should receive and process;

  SOAP encoding rules: it defines a serialization mechanism for representing the instance of the data type of the application needs to use;

  SOAP RPC: shows a protocol for representing remote procedure calls and responses;

  SOAP Binding: It defines which protocol to use SOAP to exchange information. Use Http / TCP / UDP can be. Consistent with the concepts in WCF bindings.

  In other words, SOAP protocol message used only to encapsulate, you message encapsulation may be transmitted by a variety of conventional protocols, such as Http, Https, Tcp, UDP, SMTP, etc., or you can also customize the protocol. However, the use of Web Service is based on Http protocol to transmit data.

  • UDDI: Universal Description, Discovery and Integration (Universal Description, Discovery, and Integration) acronym, it is based on a description specifications cross-platform XML, it can enable enterprises worldwide publishing services for its own provided on the Internet other customer queries.

  • WSDL: the Web Services Description Language (Web Services Description Language), an XML format for describing Web service publication. It is used to describe details of the access method using the protocol and server port, commonly used to aid the production server and the client code and configuration information.

2.2 Web Services implementation process

   Call the implementation of Web Services and similar conventional method invocation. Different is that the former method is not located in the client application, but generated by specifying the transfer protocol request message. Because Web Services may be located on different machines, and therefore must be handled Web Services request is transmitted to the information required by the server containing the Web Services network, Web Services after processing information, it sends the results back to the client application over the network. The following figure shows the communication process between the client and the Web Services:

 

  Here at Web Services calls upon sequence of events:

  1. On the client, create an instance of a Web Services proxy class. The objects residing on the client machine.

  2. The client calls the method on the proxy class

  3. The client machine parameters into a sequence of Web Services method SOAP message, and sent to the Web Services via transport protocol.

  4. Web Services and receive SOAP messages substructure deserialized. It creates an instance of the class of Web Services, and Web Services calls the corresponding method.

  5. Web Services method executes and returns the result.

  6. Web Services substructure sequence will return the result into SOAP messages, and then sent back to the client via the network.

  7. The client receives the SOAP message, and then deserialize the XML return value or any output parameters and passes them to the proxy class instance.

  8. The client receives all output parameters and return values.

2.3 Web Services advantages and disadvantages

   After the above detailed description, Web Services obviously has the following advantages:

  • Cross-platform: Web Services based entirely on XML (Extensible Markup Language), XSD (XMLSchema) and other platform-independent industry standard.

  • Self Description: Web Service using WSDL self-description, including service methods, parameters, and return value type and other relevant information.

  • Across the firewall: Web Service using the http protocol for communication, can pass through the firewall.

  Web Services also has the following disadvantages:

  • Inefficient, not suitable for the development of a single application system.

  • Security issues: Web Services without its own security mechanisms, such as Http protocol or must use IIS host program to achieve information security encryption.

Third, the use of Web Services to develop distributed applications

   Use Web Services to develop distributed applications than MSMQ and .NET Remoting is relatively simple and a lot of today's example program in three steps:

  1. Creating a project WebServiceUserValidation implement user authentication information. Specific implementation code is shown below:

 1 namespace WebServiceUserValidation
 2 {
 3     public class UserValidation
 4     {
 5         // 判断用户名和密码是否有效
 6         public static bool IsUserLegal(string name, string psw)
 7         {
 8             // 用户可以访问数据库进行用户和密码验证
 9             // 这里仅仅作为演示
10             string password = "LearningHard";
11             if (string.Equals(password, psw))
12             {
13                 return true;
14             }
15             else 
16             {
17                 return false;
18             }
19         }
20 
21         // 判断用户的凭证是否有效
22         public static bool IsUserLegal(string token)
23         {
24             // 用户可以访问数据库进行用户凭证验证
25             // 这里只做演示
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. Create a Web Services Service category, you need to create a class that inherits from SoapHeader, in advance to receive SOAP messages, and add WebServiceUserValidation assembly. Web Services to create a service project by adding an empty Asp.net Web applications, Web application project and then add the right to create a Web service file to create the Web service. Specific implementation code is shown below:

 1 // 用户自定义的SoapHeader类必须继承于SoapHeader
 2     public class MySoapHeader : SoapHeader
 3     {
 4         // 存储用户凭证
 5         public string Token { get; set; }
 6     }
 7  /// <summary>
 8     /// LearningHardWebService 的摘要说明
 9     /// </summary>
10     [WebService(Namespace = "http://www.cnblogs.com/zhili/")]
11     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12     [System.ComponentModel.ToolboxItem(false)]
13     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
14     // [System.Web.Script.Services.ScriptService]
15     public class LearningHardWebService : System.Web.Services.WebService
16     {
17         // 存储用户凭证的Soap Header信息
18         // 必须保证是public和字段名必须与SoapHeader("memberName")中memberName一样
19         // 否则会出现“头属性/字段 LearningHardWebService.authenticationToken 缺失或者不是公共的。”的异常
20         public MySoapHeader authenticationToken; 
21         private const string TOKEN = "LearningHard"; // 存储服务器端凭证
22         
23 
24         // 定义SoapHeader传递的方向
25         //SoapHeaderDirection.In;只发送SoapHeader到服务端,该值是默认值
26         //SoapHeaderDirection.Out;只发送SoapHeader到客户端
27         //SoapHeaderDirection.InOut;发送SoapHeader到服务端和客户端
28         //SoapHeaderDirection.Fault;服务端方法异常的话,会发送异常信息到客户端
29         [SoapHeader("authenticationToken", Direction = SoapHeaderDirection.InOut)]
30         [WebMethod(EnableSession = false)]
31         public string HelloLearningHard()
32         {
33             if (authenticationToken != null && UserValidation.IsUserLegal(authenticationToken.Token))
34             {
35                 return "LearningHard 你好,调用服务方法成功!";
36             }
37             else
38             {
39                 throw new SoapException("身份验证失败", SoapException.ServerFaultCode);
40             }
41         }
42     }

  In the above code should be noted that, Web methods in the Web Servies requires an exception to be thrown SoapExcetion to capture the client, if the debugger is running, then in Debug mode, you also need to set an exception in this abnormal check out that the compiler does not capture the anomaly.

  3. Create a console client to add Web Services by way of adding a service reference, after the addition is successful, will create a proxy class in the client program, the client can invoke Web Services methods through the proxy class, concrete implementation code is shown below:

 1 namespace WebServiceClient
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             // 实例化一个Soap协议的头
 8             MySoapHeader mySoapHeader = new MySoapHeader() { Token = "LearningHard"};
 9             string sResult = string.Empty;
10             LearningHardWebServiceSoapClient learningHardWebSer = null;
11             try
12             {
13                 // 实例化Web服务的客户端代理类
14                 learningHardWebSer = new LearningHardWebServiceSoapClient();
15                 // 调用Web服务上的方法
16                 sResult= learningHardWebSer.HelloLearningHard(ref mySoapHeader);
17                 // 输出结果
18                 Console.WriteLine(sResult);
19             }
20             catch
21             {
22                 Console.WriteLine("调用Web服务失败!");
23             }
24             finally
25             {
26                 // 释放托管资源
27                 if (learningHardWebSer != null)
28                 {
29                     learningHardWebSer.Close();
30                 }
31             }
32 
33             Console.WriteLine("请按任意键结束...");
34             Console.ReadLine();
35         }
36     }
37 }

  For more information about Web Services exception trapping can refer to MSDN: Handling and Throwing Exceptions in XML Web services in. However, the sample code in this MSDN seems to run is unsuccessful, the latter found that the article on exception handling client only handled SoapException exceptions, but this time FaultException abnormal abnormal client triggered, so the exception handling code should be like the following code is the same process, of course, can only deal directly exception abnormal, I will only deal with abnormal code above this large range.

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

  After the above steps, we have completed all of the development work, run the following test to run under the effect of the program. The WebServiceClient as a startup project, press F5 or Ctrl + F5 to run the client program, you will see the results as shown below:

  Note : like most distributed applications, all applications running on the server side first, and then running the client to access the service method. And here we run it directly run the client can access the Web methods in the Web Services. This is because prior to running the Web Services client program will first deploy Web Services to IIS Express, you will see the bottom right corner of the task bar there , right on the icon you can see the running Web Services.

IV Summary

   Here to share Web Services technology to end, from the beginning of the next article, we will officially enter the WCF world. The contents of the Web Services and WCF content, like a lot, but Microsoft officials recommend using WCF to create a Web service program.

 

Transfer: https: //www.cnblogs.com/zhili/p/MSMQ.html, Author: Learning hard.

If infringement, please contact me to delete!

Guess you like

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