How to "Turn" ASP. NET Web Services works

Source: Internet
Author: User
Tags wsdl

Go to http://www.cnblogs.com/zhaozhan/archive/2010/10/17/1853780.html Learn how Microsoft ASP. NET Web service method (WebMethod) is for building web Services provide an efficient approach. WebMethod can expose traditional Microsoft. NET methods to WEB service operations that support HTTP, XML, XML Schemas, SOAP, and WSDL. The WebMethod (. asmx) handler automatically dispatches the incoming SOAP message to the appropriate method and automatically serializes the incoming XML element into the corresponding. NET object. (20 printed pages) applies to: Microsoft? ASP. Web service method SOAP Message Processing XML Schema HTTP-based WEB service * Introduction to WebMethod Framework WebMethod Framework message Dispatch message dispatch XML to object map XML to object to automatically generate WSDL Automatic generation of WSDL Summary Summary resource resource introduction in Microsoft? NET, there are currently two distinct ways to implement HTTP-based WEB services. The first and lowest-level approach is to write a custom IHttpHandler class and insert it into the. NET HTTP pipeline. This approach requires that you use the System.Web API to process incoming HTTP messages and use the System.Xml API to handle the SOAP wrappers found in the HTTP body. Writing a custom handler also requires you to manually write a WSDL document that accurately describes your implementation. To do this correctly, you need to have an in-depth understanding of XML, XSD, SOAP, and WSDL specifications, but this precondition is daunting for most people. A more efficient way to implement WEB services is to use the Microsoft ASP. WebMethod Framework. The ASP. ASMX endpoint comes with a special IHttpHandler class (named Webservicehandler) that provides the reusable XML, XSD, SOAP, and WSDL functionality you need. Because the WebMethod framework frees you from complex underlying XML technologies, you can quickly focus on the business problem at hand. Figure 1. The tradeoff between flexibility and productivity is that the choice between implementation technologies will create the flexibility and productivity shown in 1A common tradeoff between the two. Writing a custom IHttpHandler gives you great flexibility, but it takes a lot of time to write, test, and debug your code. The WebMethod framework makes it easy to quickly build and run Web services, but you will undoubtedly be constrained by the boundaries of that framework. However, if the WebMethod framework does not fully meet your needs, you can also extend the framework by adding your own additional features. In general, unless you have mastered XML, XSD, SOAP, and WSDL and are willing to take the burden of dealing directly with them, it is best to use the WebMethod framework to meet your WEB service needs. It provides the basic services required for most WEB service endpoints, and some interesting extensibility features that make the framework more consistent with your exact needs. Based on the above assumptions, the remainder of this article will discuss the internal working mechanism of WebMethod. If you are unfamiliar with XML schemas and SOAP, you may need to refer to understanding XML Schema and understanding soap before continuing to read this article. Returns to the top WebMethod Framework WebMethod Framework is designed around the way a SOAP message is mapped to a method on a. NET class. This is done by first annotating your method with the [WebMethod] property found in the System.Web.Services \ namespace. For example, the following. NET class contains four methods, of which two methods are annotated with the [WebMethod] property: Using System.Web.Services; public class MathService {[WebMethod] public double Add (double x, double y) {return x + y;} [WebMethod] public double Subtract (double x, double y) {return x-y;} public double Multiply (double x, double y) {Retu RN x * y; } public double Divide (double x, double y) {return x/y;}} To use the class in the WebMethod framework, you need to compile the class into an assembly and then copy it to the bin directory of the virtual directory. In this example, the add and Subtract methods can then be exposed as WEB service operations, and MulTiply and Divide are not (because they are not labeled as [WebMethod]). The ADD and Subtract are exposed as WEB service operations through the. ASMX endpoint. To do this, create a new text file named Math.asmx that contains the following simple declaration, and then place it in the same virtual directory that contains the assembly (note: This is placed in the virtual directory itself, not its bin subdirectory): <%@ WebService class= " MathService "%> notice above the declaration that the ASMX handler is going to find WebMethod in which class, the handler magically handles everything else. For example, assuming that the name of the virtual directory is ' math ', which contains math.asmx and a bin subdirectory containing the assembly, browsing to Http://localhost/math/math.asmx causes the. asmx handler to generate the document page shown in 2 (the following Detailed). There is a big change in how the. asmx handler works. The. asmx file typically contains only the WebService declaration, which references the Web service class by name (this is similar to the declaration shown above). Therefore, in this case, the assembly must have been compiled and deployed to the bin directory of the virtual directory. For source code found in the. asmx file, the. asmx handler also provides real-time compilation. For example, the following file (named Mathjit.asmx) contains the WebService declaration and the source code of the referenced class. <@% WebService class= "Mathservicejit" language= "C #"%> using System.Web.Services; public class Mathservicejit {[WebMethod] public double Add (double x, double y) {return x + y;} [WebMethod] public double Subtract (double x, double y) {return x-y;} public double Multiply (double x, double y) {Retu RN x * y; } public double Divide (double x, double y) {return x/y;}} When this is first accessed over HTTPFile, the. asmx handler compiles the source code and deploys the assembly to the correct location. Note that the WebService declaration must also provide the language so that the. asmx handler can select the correct compiler at run time. The obvious disadvantage of this approach is that compilation errors are found only after the first access to the file. Figure 2. MathService documents when you create a new WEB service project in Visual Studio. NET, you always use the "dual file" technique, which is that the source file for the class is separate from the. asmx file that references it. The integrated development Environment (IDE) hides files as much as possible, but if you click Show All files on the Solution Explorer toolbar, you will notice that each Web service class in the project has two files. In fact, Visual Studio. NET does not support syntax highlighting or IntelliSense for. asmx files, so if you are designing in this direction, you must rely on yourself. For WEB projects, Visual Studio. NET is also responsible for automatically creating a virtual directory and compiling the assembly into the bin directory of the virtual directory. Before discussing in detail how the ASMX handler works, let's briefly discuss how the message is passed from Internet information Server (IIS) to the. asmx handler. When an incoming HTTP message arrives at port 80 O'Clock, IIS uses the information found in the IIS metabase to determine which ISAPI DLL should be used to process the message. The. NET installer maps the. asmx extension to Aspnet_isapi.dll, as shown in 3. Figure 3. The. asmx IIS application mapping Aspnet_isapi.dll is the standard ISAPI extension provided by the. NET framework, which simply forwards the HTTP request to a separate worker process named aspnet_wp.exe. aspnet_wp.exe hosts the common language runtime and the. NET HTTP pipeline. When a message enters the. NET HTTP pipeline, the pipeline looks in the configuration file to see which IHttpHandler class should be used for the given extension. If you are looking in the Machine.config file, you will find that it contains the HttpHandler mapping for the. asmx file, as follows: ... Therefore, when a message enters a. NET HTTP pipeline that targets an. asmx file, the pipeline invokes the Webservicehandlerfactory class to instantiate a new Webservicehandler object that can be used to process the request (by invoking the Ihttphandlerprocessrequest method). The Webservicehandler object then opens the physical. asmx file to determine the name of the class that contains the WebMethod. For more information about how the. NET HTTP pipeline Works, see HTTP pipelines:securely Implement Request processing, Filtering, and Content redirection with HTTP pipelines in ASP. After the. asmx handler is called by the. NET HTTP pipeline, it begins to magically process XML, XSD, SOAP, and WSDL. The remaining functionality provided by the. asmx handler can be divided into three main classes: 1) message scheduling, 2) mapping XML to an object, 3) automatically generating WSDL and documentation. Let's look at these aspects in more detail. Returns the top of page message dispatch when the. asmx handler is called by an HTTP pipeline, it determines which. NET class to check by looking at the WebService declaration found in the. asmx file. It then looks at the information in the incoming HTTP message to correctly determine which method to invoke in the referenced class. To invoke the ADD operation shown in the previous example, the incoming HTTP message must look like the following: Post/math/math.asmx http/1.1 host:localhost content-type:text/xml; Charset=utf-8 content-length:length soapaction: "Http://tempuri.org/Add" about In an incoming HTTP message, it is true that two pieces of information are available to determine which method to invoke in the class: the SOAPAction header or the name of the requested element (for example, the name of the element in the Soap:body element). In this case, either one indicates the name of the method the sender wants to invoke. By default, the. asmx handler uses the value of the SOAPAction header to perform a message dispatch. Therefore, the. asmx handler looks at the SOAPAction header in the message and examines the methods in the referenced class using. NET reflection. It only considers methods that mark the [WebMethod] property, but it can correctly determine which method to invoke by looking at the SOAPAction value of each method. Because we do not explicitly specify the SOAPAction value for a method in a class, the. asmx handler assumes that the SOAPAction value will consist of the Web service's namespace and its subsequent method names. And we don't specify a namespace, so the handler will http://tempuri.org as the default namespace. This way, the default SOAPAction value of the Add method will be http://tempuri.org/Add. You can customize the namespace of your Web service by annotating your own WebMethod with the [SoapDocumentMethod] property, using the [WebService] property and the correct SOAPAction value to annotate your own class, as follows: using System.Web.Services; Using System.Web.Services.Protocols; [WebService (namespace= "Http://example.org/math")] public class MathService {[WebMethod] public double Add (double X, Double y) {return x + y;} [WebMethod] [SoapDocumentMethod (action= "Urn:math:subtract")] public double subtract (double x, double y) {return x-y;} ...} Now, the. asmx handler expects the SOAPAction value of the Add method to be HTTP://EXAMPLE.ORG/MATH/ADD (using the default heuristics) and wants the Subtract method SThe Oapaction value is urn:math:subtract (because we explicitly define it as this value). For example, the following HTTP request message calls the Subtract operation: post/math/math.asmx http/1.1 host:localhost content-type:text/xml; Charset=utf-8 content-length:length soapaction: "Urn:math:subtract" $ If the. asmx handler does not find a soapaction that matches the incoming HTTP message, it simply throws an exception, which in the future details how to handle the exception. If you do not want to rely on the SOAPAction header for method scheduling, you can use the Routingstyle property of the [SoapDocumentService] property to annotate the class to indicate that the. asmx handler uses the name of the requested element. If you do this, you might also indicate that WebMethod does not require SOAPAction values (by setting their values to an empty string), as follows: using System.Web.Services; Using System.Web.Services.Protocols; [WebService (namespace= "Http://example.org/math")] [SoapDocumentService (Routingstyle=soapserviceroutingstyle.requestelement)] public class MathService {[WebMethod] [ SoapDocumentMethod (action= "")] public double Add (double x, double y) {return x + y;} [WebMethod] [SoapDocumentMethod (action= "")] public double Subtract (double x, double y) {return x-y;} ...} In this case, the handler does not even look at the SOAPAction value, but instead uses the name of the requested element. For example, for the Add method, the handler expects the name of the requested element to be ADD (from the Http://example.org/math namespace), as shown in the following HTTP request message: Post/math/math.asmx http/1.1 host:l Ocalhost Content-type:text/xml; Charset=utf-8 content-length:length soapaction: "" 66 Therefore, when the. asmx handler receives an incoming HTTP message, the first thing it does is determine how to dispatch the message to the appropriate WebMethod. However, before the method can actually be called, it must map the incoming XML to a. NET object. Back to the top of the page to map XML to an object after the Webmehod handler determines the method to invoke, it needs to deserialize the XML message into a. NET object that can be provided during the method call. As with message scheduling, the handler does this by examining the class through reflection to determine how the incoming XML message is processed. The XmlSerializer class automates mapping between Xml and objects in the System.Xml.Serialization namespace. XmlSerializer makes it possible to map any public. NET type to an XML Schema type, and after such a mapping is established, it can be automatically mapped between. NET objects and XML instance documents (see Figure 4). Currently, XmlSerializer is limited to the models supported by the XML schema, so it is not possible to handle all of today's complex modern object models, such as complex, non-tree object graphs, double pointers, and so on. However, XmlSerializer is able to handle most of the complex types that developers tend to use. For the add example described above, XmlSerializer maps the x and Y elements to. NET double values, which are then provided when the add is called. The Add method returns a double value to the caller that will then need to be serialized back into an XML element in the SOAP response. Figure 4. Mapping XML to an object XmlSerializer also automates the processing of complex types (in addition to the limitations described above). For example, the following WebMethod calculates the distance between two point structures: using System; Using System.Web.Services; public class Point {public double X; public double y;} [WebService (namespace= "Urn:geometry")] public class Geometry {[WebMethod] public double Distance (point orig, point dest) {return math.sqrt (Math.pow (Orig.x-dest.x, 2) + MAth. Pow (ORIG.Y-DEST.Y, 2)); The SOAP request message for this operation will contain a Distance element that contains two child elements, one called orig, and the other called dest, which should contain the X and Y child elements as follows: 0 0 3 4 In this case, the SOAP response message will contain a distanceresponse element that contains a distanceresult element of a double type: 5 The default XML map uses the name of the method as the name of the requested element, using the name of the parameter as the name of the child element of the request element. The structure of each parameter depends on the structure of the type. The names of public fields and properties are only mapped to child elements (in this case, X and y in point). By default, the name of the response element is appended with "Response" after the name of the requested element. The response element also contains a child element, with the name appended with "Result" after the name of the requested element. You can free up the standard XML map by using a number of built-in mapping properties. For example, you can use the [XmlType] property to customize the name and namespace of a type. You can use the [XmlElement] and [XmlAttribute] properties to control how parameters or class members are mapped to elements or attributes, respectively. You can also use the [SoapDocumentMethod] property to control how the method itself maps to the element name in the request/Response message. For example, check the following version of the distance:using System using a variety of properties scattered in the program fragment below; Using System.Web.Services; Using System.Web.Services.Protocols; Using System.Xml.Serialization; public class Point {[XmlAttribute] public double x; [XmlAttribute] public double y; } [WebService (namespace= "Urn:geometry")] public class Geometry {[WebMethod] [SoapDocumentMethod (Requestelementname=] Calcdistance ", responseelementname=" Calculateddistance ")] [Return:xmlelement (" result ")] public double Distance ([ XmlElement ("O")]point orig, [XmlElement ("D")]point dest) {return math.sqrt (Math.pow (Orig.x-dest.x, 2) + Math.pow ( ORIG.Y-DEST.Y, 2)); }} This version of Distance wants to pass in a SOAP message with the following appearance: Also, it generates a SOAP response message that looks like this: 5 The. asmx handler uses the SOAP document/literal style to implement and describe the default mappings shown above. This means that the WSDL definition will contain the literal XML schema definition used to describe the request and response elements used in the SOAP message (for example, do not use SOAP encoding rules). The. asmx handler can also use the SOAP rpc/encoded style. This means that the SOAP body contains an XML representation of an RPC call, and the parameters are serialized using SOAP encoding rules (for example, XML Schemas are not required). To achieve this goal, you can use the [SoapRpcService] and [SoapRpcMethod] properties instead of the [SoapDocumentService] and [SoapDocumentMethod] properties. For more information about the differences between these styles, see Understanding SOAP. As you see, you can completely customize how a given method maps to a SOAP message. XmlSerializer provides a powerful serialization engine, as well as many features that we don't have time to discuss in this article. For more information on how XmlSerializer works, see moving to. NET and Web Services. In my monthly MSDN Magazine XML Files column (which can be viewed in the online archive), I've also covered many subtle nuances of XmlSerializer. In addition to processing the deserialization of a parameter, the. asmx handler is also able to deserialize/serialize the SOAP header. SOAP headers are handled differently than parameters because they are often treated as out-of-band information and are not directly related to a particular method. Therefore, the processing of the SOAP header is usually done through the listening layer, which makes the WebMethod completely unnecessary to process the SOAP header. However, if you want to handle the header information in WebMethod yourself, you must provide a. NET class derived from SoapHeader that represents the XML schema type of the header (following the same mapping guidelines described above). Then define the member variable of the type so that it acts as a placeholder for the head instance. Finally, annotate each WebMethod that needs to access the header to specify the name of the field you want to reach. For example, consider the following SOAP request, which contains a UsernameToken header for authentication: Mary Yram ... In order for the. asmx handler to deserialize the header, you first need to define a. NET class that represents the implicit XML Schema type (note: If you actually know the XML schema for the header, you can use XSD.EXE/C to generate the class). In this example, the corresponding class looks as follows: [XmlType (namespace= "http://example.org/security")] [XmlRoot (namespace= http://example.org/ Security ")] public class Usernametoken:soapheader {public string username; public string Password;} Then, just in the WebMethod class Defines a member variable to hold an instance of the header class, annotated with the [SoapHeader] property WebMethod, as follows: using System; Using System.Web.Services; Using System.Web.Services.Protocols; [WebService (namespace= "Urn:geometry")] public class Geometry {public UsernameToken Token; [WebMethod] [SoapHeader ("Token")] public double Distance (point orig, point dest) {if (! Token.username.Equals (Reverse (Token.password))) throw new Exception ("Access Denied"); Return Math.sqrt (Math.pow (Orig.x-dest.x, 2) + Math.pow (ORIG.Y-DEST.Y, 2)); You can then access the Token field in WebMethod and extract the information provided in the header. You can also resend the header to the client using the same method-you only need to specify the direction of the header in the [SoapHeader] property. For more information about working with SOAP headers in the WebMethod framework, see digging into soap Headers with the. NET Framework: ASMXThe handler also provides automatic serialization of. NET exceptions. Any unhandled exception caught by the. asmx handler is automatically serialized into the soap Fault element in the response. For example, in the previous example, if the user name does not match the reverse password, the code throws a. NET exception: The ASMX handler then captures the exception and serializes it into a SOAP response, as follows. s Oap:server Server was unable to process request.-Access Denied If you want more control over the soap Fault element, you can also explicitly raise the SoapException object to specify all of the soap Fault element details, such as FaultCode, Faulstring, Faultactor, and The detail element. For more information, see Using SOAP faults. As you can see, it is important to understand how WebMethod works and the underlying serialization engine and its various options. The advantage of the serialization engine is that it hides all the underlying XML API code, and in a custom handler, you typically have to write the code. Although most developers find this to be good, some developers consider it a flaw because they still want to handle the original SOAP message in the WebMethod implementation themselves. For more detailed information on how to implement this hybrid approach, see Accessing Raw SOAP Messages in ASP. Back to the top of the page auto-generated WSDL after you have written and deployed WebMethod, the client needs to know exactly what the SOAP message must look like in order to successfully communicate with it. The standard way to provide a description of a Web service is through WSDL (and the embedded XSD definition). To help accommodate this situation, the. asmx handler automatically generates a readable document page and a WSDL definition that accurately reflects the WebMethod interface. If you apply many of the mapping properties to WebMethod, they are reflected in the generated document. If you browse the. asmx file, you will see a 2 document page that can be manually read. This document page is generated by an. aspx page named DefaultWsdlHelpGenerator.aspx (located in C:\windows\Microsoft.NET\Framework\ v1.0.3705\config). If you open this file, you will find that this is just a standard ASP. NET page, which generates a document using. NET reflection. This feature allows your documents to always stay in sync with your code. You can customize the resulting document by simply modifying the file. You can also avoid generating documents in a virtual directory by specifying a different document file in the Web. config file: ... If the client issues a GET request to the. ASMX endpoint, and there is "? wsdl" in the query string, the. asmx handler generates the WSDL definition without generating a document that can be manually read. Clients can use WSDL definitions to generate proxy classes that automatically learn how to communicate with Web services (for example, using Wsdl.exe in. NET). To customize the WSDL generation process, you can write a SoapExtensionReflector class and register the class with the WebMethod framework in the Web. config file. Then, when the. asmx handler generates the WSDL definition, it invokes the reflector class and gives you the opportunity to customize the final definition that is provided to the client. For more information about how to write the SoapExtensionReflector class, see Soapextensionreflectors in ASP. You can also use two different methods to completely skip the WSDL generation process. The first approach is to provide a static WSDL document that is accessible to the client in the virtual directory and then disable it by removing the document generator from the Web. config file, as follows: ... Another way to be more automated is to use the [Webservicesbinding] property to specify the location of the static WSDL document implemented by the WebMethod class in the virtual directory. You must also specify a name for the WSDL binding implemented by each WebMethod using the [SoapDocumentMethod] property. When you do this, the WSDL auto-generation process imports the static WSDL file and wraps a new service description around it. For more information about this method, see the article titled Place XML Message Design Ahead of the Schema planning to Improve Web Service interoperability. Currently, it is extremely difficult to write WSDL manually because there are still not too many WSDL editors available. Therefore, the automatic generation of document/WSDL is a valuable part of the WebMethod framework, and without it, many developers will be sad. Back to top Summary the ASP. NET WebMethod Framework provides an efficient way to build WEB services. The WebMethod framework makes traditional. NET methods exposed to WEB service operations that support HTTP, XML, XML Schemas, SOAP, and WSDL. The WebMethod (. asmx) handler automatically determines how the incoming SOAP message is dispatched to the appropriate method, and when the incoming XML element is automatically serialized to the appropriate. NET object. Also, to simplify integration with clients, the. asmx handler provides automatic support for generated human-readable (HTML) and machine-readable (WSDL) documents. Although the WebMethod framework is slightly more restrictive than the custom IHttpHandler, it provides a powerful extensibility model, known as the SOAP extension framework. The SOAP extension allows you to introduce additional features that we didn't discuss above to meet your specific needs. For example, Microsoft publishes Web Services Enhancements 1.0 for Microsoft. NET (WSE), and WSE provides only one SoapExtension class, which introduces several G to the WebMethod framework Support for the XA specification. For more information about writing a SOAP extension, see the fun with soap Extensions. Original: HTTP://MSDN.MICROSOFT.COM/ZH-CN/library/ms996410.aspx

"Go" how ASP. NET Web Services works

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.