First, Introduction
The MSMQ and. NET Remoting technologies are described in the previous article, and today we continue to share another distributed technology--web Services under the. NET Platform.
Second, Web Services Details 2.1 Web Services Overview
WEB Services is a software system that enables clients to interoperate with servers over a network, and is a set of application APIs that can be called over the network. Among the three core concepts of Web services, mainly to SOAP/UDDI/WSDL, the following are the definitions of these three concepts.
- Soap:soap (Simple Object access Protocol) is a simple protocol for exchanging information in a decentralized or distributed environment, an XML-based protocol that requires binding a network transport protocol to complete the transmission of information. This protocol is usually HTTP or HTTPS, but it can also make other protocols.
It consists of four parts:
SOAP encapsulation: It defines a framework that describes what the message is describing, who sent it, and who should receive and process it;
SOAP Encoding Rules: Defines a mechanism for serialization that represents an instance of the data type that the application needs to use;
SOAP RPC: Represents a contract that represents a remote procedure call and response;
SOAP binding: It defines which protocol soap uses to exchange information. You can use HTTP/TCP/UDP. is consistent with the concept of binding in WCF.
In other words, the SOAP protocol is only used to encapsulate the message, and the encapsulated message can be transmitted through a variety of existing protocols, such as HTTP, Https, TCP, UDP, SMTP, and even you can customize the protocol. Web service, however, uses HTTP-based protocols to transmit data. A way to access Web services using the HTTPS protocol can be found in this article: How to invoke a Web service with SSL.
- UDDI: is the abbreviation for Unified Description, Discovery, and integration (Universal Description, Discovery, and integration), which is an XML-based cross-platform description specification, It allows companies worldwide to publish their services on the Internet for other customers to inquire about.
- WSDL: Is the Web Service Description Language (Web Services Description Language), which is the XML format published for the description Web service. Describes the details of how the server port is accessed and uses protocols, and is typically used to assist in the production server and client code and configuration information.
2.2 Web Services Implementation process
Invoking a Web services implementation is similar to making a regular method call procedure. The difference is that the former method does not reside in the client application, but instead generates the request message by specifying the transport protocol. Because Web services may reside on different computers, the information required to process requests for Web services must be passed over the network to the server that contains the Web services, and after the Web service processes the information, The results are sent back to the client application over the network. Shows the communication process between the client and the Web services:
The following describes the order in which events occur when you downgrade Web services:
- On the client, an instance of the Web services proxy class is created. The object resides on the client machine.
- Methods on the client invoke proxy class
- The client machine serializes the parameters of the Web Services method into a SOAP message, which is then sent to the Web services through a routing protocol.
- The WEB services underlying structure receives and deserializes the SOAP message. It creates an instance of the Web services class, and calls the corresponding Web services method.
- The Web services method executes and returns the result.
- The WEB services underlying structure serializes the returned result into a SOAP message and then sends it back to the client over the network.
- The client receives the SOAP message and then deserializes the XML back into the return value or any output parameters and passes them to the instance of the proxy class.
- The client receives the return value and all output parameters.
2.3 Web Services Pros and cons
After a detailed introduction, WEB services clearly has the following advantages:
- Cross-platform: Web Services is based entirely on platform-agnostic industry standards, such as XML (Extensible Markup Language), XSD (XmlSchema), and so on.
- Self-Description: The WEB service uses WSDL to describe itself, including information about the methods, parameters, types, and return values of the service.
- Cross-firewall: Web service communicates using the HTTP protocol and can traverse firewalls.
WEB Services also have the following drawbacks:
- Inefficient, not suitable for the development of single-application systems.
- Security issue: WEB Services does not have its own security mechanism and must implement information security encryption with host programs such as the HTTP protocol or IIS.
Iii. using Web services to develop distributed applications
Using Web services to develop distributed applications is a lot simpler than MSMQ and. NET remoting, and today's sample programs take three steps:
- Create a project webserviceuservalidation that implements user information validation. The specific implementation code is as follows:
1 namespacewebserviceuservalidation2 {3 Public classuservalidation4 {5 //determine if the user name and password are valid6 Public Static BOOLIsuserlegal (stringNamestringPSW)7 {8 //users can access the database for user and password authentication9 //here just as a demoTen stringPassword ="Learninghard"; One if(string. Equals (password, PSW)) A { - return true; - } the Else - { - return false; - } + } - + //determine if the user's credentials are valid A Public Static BOOLIsuserlegal (stringtoken) at { - //users can access the database for user credential validation - //just a demo here. - stringPassword ="Learninghard"; - if(string. Equals (password, token)) - { in return true; - } to Else + { - return false; the } * } $ }Panax Notoginseng}
2. To create a Web Services service class, you need to create a inherit from SoapHeader to receive the message from the SOAP header and add the Webserviceuservalidation assembly. Create a Web service by adding an ASP. NET empty Web application to create a Web Services service project, and then right-creating the Web application project to add a Web service file. The specific implementation code is as follows:
//the user-defined SoapHeader class must inherit from the SoapHeader Public classMysoapheader:soapheader {//Store user Credentials Public stringToken {Get;Set; } } /// <summary> ///Summary description of Learninghardwebservice/// </summary>[WebService (Namespace ="http://www.cnblogs.com/zhili/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)] //To allow this Web service to be called from a script using ASP. NET AJAX, uncomment the following line. //[System.Web.Script.Services.ScriptService] Public classLearningHardWebService:System.Web.Services.WebService {//SOAP header information for storing user credentials//must be guaranteed to be public and field names must be the same as membername in SoapHeader ("MemberName")//Otherwise, the header attribute/field Learninghardwebservice.authenticationtoken is missing or not public. "The exception PublicMysoapheader Authenticationtoken; Private Const stringTOKEN ="Learninghard";//Storage server-side credentials//defining the direction of SoapHeader delivery//soapheaderdirection.in; Send SoapHeader to server only, this value is the default value//soapheaderdirection.out; Send SoapHeader to client only//soapheaderdirection.inout; Send SoapHeader to server and client//Soapheaderdirection.fault, if the service-side method is abnormal, it sends the exception message to the client.[SoapHeader ("Authenticationtoken", Direction =soapheaderdirection.inout)] [WebMethod (EnableSession=false)] Public stringHellolearninghard () {if(Authenticationtoken! =NULL&&Uservalidation.isuserlegal (Authenticationtoken.token)) { return "Learninghard Hello, call the service method successfully!"; } Else { Throw NewSoapException ("failed authentication", Soapexception.serverfaultcode); } } }
It is important to note in the above code that Web methods in Web servies need to throw soapexcetion exceptions to be caught by the client, and if the debug mode is down, the exception must be checked out in the exception setting, that is, the compiler does not capture the exception.
3. Create a console client, add a Web services by adding a service reference, add a success, create a proxy class in the client program, the client can invoke the Web services method through the proxy class, the implementation code is as follows:
1 namespacewebserviceclient2 {3 class Program4 {5 Static voidMain (string[] args)6 {7 //instantiate the header of a SOAP protocol8Mysoapheader Mysoapheader =NewMysoapheader () {Token ="Learninghard"};9 stringSresult =string. Empty;TenLearninghardwebservicesoapclient Learninghardwebser =NULL; One Try A { - //Instantiate the client proxy class for a Web service -Learninghardwebser =Newlearninghardwebservicesoapclient (); the //invoke a method on a Web service -sresult= Learninghardwebser.hellolearninghard (refmysoapheader); - //Output Results - Console.WriteLine (sresult); + } - Catch + { AConsole.WriteLine ("failed to invoke Web service!"); at } - finally - { - //Releasing managed resources - if(Learninghardwebser! =NULL) - { in learninghardwebser.close (); - } to } + -Console.WriteLine ("Please press any key to end ..."); the console.readline (); * } $ }Panax Notoginseng}
For more information about WEB Services exception trapping, refer to MSDN: Handling and Throwing Exceptions in XML Web services. However, the example code on this MSDN does not seem to run successfully, and later found that the client handling of the exception handled only the SoapException exception when the client fired the exception, so the exception handling code should be treated like the following code, which is the faultexception exception. Of course, we can deal with the exception exception directly, and the above code only handles this wide range of exceptions.
Catch (SoapException ex) { // } catch (Exception ex) { // do sth with Exception }
Through the above steps, we have completed all the development work, the following run to test the performance of the program. To run the client program as a startup project and press F5 or CTRL+F5 directly, you will see the results shown below: webserviceclient
Note: Like general distributed applications, applications run on the server side before running the client to access the service methods. This is where we run and run the client directly to access Web methods in Web services. This is because Web services is deployed to IIS Express before you run the Web Services client program, and you will see the Web services running by right-clicking the icon in the lower-right corner of the taskbar.
Iv. Summary
Here, the sharing of WEB services technology is over, starting with the next article, will formally enter the world of WCF. The content of Web services is much the same as WCF content, but Microsoft officially recommends using WCF to create Web services programs, and if you want to learn more about the content of Web services, you can refer to MSDN: XML Web created with ASP. Services and XML Web Services clients
all sample code downloads for this article: Webservicesample
Learn with me WCF (3)-Developing distributed applications with Web services