Developing distributed applications with Web services

Source: Internet
Author: User
Tags soap server port msmq wsdl

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:

    1. On the client, an instance of the Web services proxy class is created. The object resides on the client machine.
    2. Methods on the client invoke proxy class
    3. 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.
    4. 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.
    5. The Web services method executes and returns the result.
    6. The WEB services underlying structure serializes the returned result into a SOAP message and then sends it back to the client over the network.
    7. 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.
    8. 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:

    1. Create a project webserviceuservalidation that implements user information validation. The specific implementation code is as follows:
1 namespace webserviceuservalidation 2 {3 Public     class Uservalidation 4     {5         //Determine if user name and password are valid 6 public         stat  IC bool Isuserlegal (string name, String psw) 7         {8             //Users can access the database for user and password Authentication 9             //Here just as a demo of the             string password = "Learninghard";             Equals (password, PSW))             {                 return true;14             }15 Else-                 false;18             }19         }20         //Determine if the user's credentials are valid. Public         static bool Isuserlegal (string token)             Users can access the database for user credential verification             .//Here only do a demo of             string password = "Learninghard";             Equals (password, token)) (                 true;30             }31             else32             {return                 false;34             }         }36     }37}

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:

 1//user-defined SoapHeader class must inherit from SoapHeader 2 public class Mysoapheader:soapheader 3 {4//Storage User Credential 5 public string Token {get; set;} 6} 7//<summary> 8//Learninghardwebservice Summary Description 9//</sum mary>10 [WebService (Namespace = "http://www.cnblogs.com/zhili/")]11 [webservicebinding (ConformsTo = WsiProfiles . basicprofile1_1)]12 [System.ComponentModel.ToolboxItem (FALSE)]13//To allow this Web service to be called from the script using ASP., uncomment the line. //[SYSTEM.WEB.SCRIPT.SERVICES.SCRIPTSERVICE]15 public class LearningHardWebService:System.Web.Services.WebSe         RVICE16 {17///store user credentials for SOAP header information 18//must be guaranteed to be public and field names must be the same as membername in SoapHeader ("MemberName") 19 Otherwise, the header attribute/field Learninghardwebservice.authenticationtoken is missing or not public. "The exception of the public Mysoapheader Authenticationtoken; Private Const string TOKEN = "Learninghard"; Storage server-side credentials 22 23 24//define the direction of SoapHeader delivery//soapheaderdirEction. In; send only soapheader to the server, this value is the default value of//soapheaderdirection.out; Send SoapHeader to client only//soapheaderdirection.inout; send SoapHeader to the server and client//soapheaderdirection.fault, the service side method exception, will send exception information to the client [SoapHeader ("Authenticationtoken" , Direction = soapheaderdirection.inout)]30 [WebMethod (enablesession = False)]31 public string Hellolearni Nghard () + {Authenticationtoken! = null && uservalidation.isuserlegal (authenticationtok En. Token) "Learninghard Hello, call the service method success!" }37 else38 {New SoapException ("Authentication failed", Soapexception.serv Erfaultcode); 40}41}42}

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 namespace WebServiceClient 2 {3 class program 4 {5 static void Main (string[] args) 6 {7 Instantiate the header of a SOAP protocol 8 mysoapheader Mysoapheader = new Mysoapheader () {Token = "learninghard"}; 9 string sresult = String.                 empty;10 learninghardwebservicesoapclient Learninghardwebser = null;11 Try12 {13                 Instantiate a client proxy class for a Web service learninghardwebser = new Learninghardwebservicesoapclient (); 15 Invoke methods on Web service sresult= Learninghardwebser.hellolearninghard (ref mysoapheader); 17/                 /Output Results Console.WriteLine (sresult),}20 catch21 {22 Console.WriteLine ("Call Web Service failed!"); }24 Finally25 {26//Release managed resource if (learninghardwebse  R! = null) learninghardwebser.close (); 30               }31}32 Console.WriteLine ("Please press any key to end ..."); Console.ReadLine (); 35 }36}37}

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)    {        //do sth with SoapException     }    catch (Exception ex)    {        //does STH with ex Ception    }

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

Developing distributed applications with Web services

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.