Application and implementation of SOAP protocol expansion
The SOAP protocol (simple object transmission) is an XML-based, simple lightweight protocol for exchange structured and type information on the web. The overall design goal of SOAP is to make it simply as possible and provide the least functionality. This protocol defines a messaging framework that does not contain any application or transmit semantics. Therefore, the protocol is modular and has strong spreadability.
The SOAP protocol specification contains four main components. The first part defines the necessary scalable envelopes for packaging data. The SOAP envelope defines the SOAP message and is the basic exchange unit between the SOAP message processor. This is the only part of this specification.
The second part of the SOAP protocol specification defines the data type defined by the application and an optional data coding rule for graphics, and a unified model for serializing non-syntax data models.
The third part defines the message exchange mode of the RPC style (request / response). Each SOAP message is one-way transmission. Although the root of SOAP is in RPC, it is just just a request / response mechanism. XML Web Services often combines SOAP messages to implement such patterns, but SOAP does not force message exchange mode, which is also optional.
The fourth part of the specification defines the binding between SOAP and HTTP. However, this part is also optional. SOAP can be used with any transport protocol or mechanism (including SMTP FTP or even floppy disk) capable of transmitting a SOAP envelope.
Microsoft implements a SOAP protocol and makes it an important basis for .NET Framework. Any Client-Server-based transmission of Microsoft.NET is in the form of SOAP. (HttpGet and Httppost protocols are just Client applications).
Have an example of .NET. For example, a Web Service program is DATA.ASMX:
<% @ Webservice Language = "C #" class = "data"%>
Using system;
Using system.Web.services;
Public Class Order
{
Public int OrderID;
Public Double Price;
}
Public class data {
[WebMethod]
Public Order GetOrder ()
{
Order myorder = new order ();
myorder.price = 34.5;
Myorder.orderid = 323232;
Return myorder;
}
}
Now use the WSDL tool to convert Web Serivce's WSDL to Client agents such as WSDL / Protocol: SOAP / NAMESPACE: D http://localhost/data1.asmx
(Suppose Data1.asmx is placed under the root of the IIS server (C: / INETPUB / WWWROOT)).
Generate a client agent Data.cs:
Namespace d {
Using system.diagnostics;
Using system.xml.serialization;
Using system;
Using system.web.services.protocols;
Using system.componentmodel;
Using system.Web.services;
///
[System.diagnostics.debuggerstepthroughattribute ()]
[System.componentmodel.designercategoryAttribute ("code")]]]]]
[System.Web.Services.WebserviceBindingAttribute (name = "datasoap", namespace = "http://tempuri.org/")] public class data: system.Web.Services.protocols.soaphttpClientProtocol {
///
Public Data () {
THIS.URL = "http://localhost/data1.asmx";
}
///
[System.Web.Services.Protocols.SoapDocumentMethodAttribute ( "http://tempuri.org/GetOrder", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System.Web.Services.Description.soapbindinguse.literal, parametersty = system.web.services.protocols.soApparameterStyle.wrapped]
Public Order GetOrder () {
Object [] results = this.invoke ("getorder", new object [0]);
Return ((ORDER) (Results [0]));
}
///
Public System.iasyncResult BegingeTorder (System.AssyncCallback Callback, Object AsyncState) {
Return this.beginInvoke ("GetOrder", New Object [0], Callback, AsyncState;
}
///
Public Order Endgetorder (System.iasyncResult asyncRESULT) {
Object [] results = this.endinvoke (asyncResult);
Return ((ORDER) (Results [0]));
}
}
///
[System.xml.serialization.xmltypeattribute (Namespace = "http://tempuri.org/")]
Public class order {
///
Public int OrderID;
///
Public system.double price;
}
}
Then compile it into a DLL. Such as: CSC / T: library /out:c:/inetpub/wwroot/bin/data.dll data.cs, you can use .NET's Client program to call (such as Winform, CS or aspx).
Here is the call to the client with Test.aspx.
<% @ Import namespace = "d"%>
Div
{
Font: 8pt Verdana;
Background-color: cccccc;
Border-color: black;
BORDER-WIDTH: 1;
Border-style: solid;
Padding: 10, 10, 10, 10;
}
style>
Public void Page_Load (Object Sender, Eventargs E)
{
Data DataType = New Data ();
Order or = datatype.getORDER ();
Response.write ("ORDER - ===" Or.Orderid "
);
}
script>
body>
html>
Run this program will print "Order ======== 323232" in the browser.
Let's study what the client is transmitted to the end of SERVER.
When we execute Test.aspx, it calls to the getorder () method of Data.cs, then serialize the information, and packaged:
XML Version = "1.0" encoding = "UTF-8"?>
Transfer to the server, after the server accepts information, deserialization, then call the getorder () method on the Server to get a return value and serialize, get a stream:
XML Version = "1.0" encoding = "UTF-8"?>
From the above analysis, the SOAP protocol is a function of transmitting data. But the transmission is complex and there are many uncertain factors. How do I treat the security? How to determine if Server is reliable? How to identify how Server CLIENT?
Microsoft launches SOAP Extension to implement the encryption and decryption of SOAP messages. As you can see the use of SOAP extensions from the figure:
As you can see, ASP.NET serializes and deserialized in the XML Web Services computer and XML Web Services client computers. The SOAP extension can be inserted into the infrastructure to check or modify the SOAP message before and after each serialization and reverse sequence phase. For example, encrypted SOAP extensions may encrypt the XML section of the SOAP message after the ASP.NET serialization client, and then decrypt SOAP messages on the web server before the ASP.NET defense SOAP message. These phases (SOAP extensions may be checked or modified in these phases) is defined in the SOAPMESSAGESTAGE enumeration. In this case, the SOAP extension is encrypted in the afterSerialize phase, and the SOAP extension is decrypted in the BeforeDeSerialize phase.
Typically, when SOAP extension changes the content of the SOAP message, you must modify it on the client and server. That is, if you want to run SOAP to extend and encrypt the SOAP message on the client, the corresponding SOAP extension must decrypt the SOAP message on the server. If the SOAP message is not decrypted, the ASP.NET infrastructure cannot be resembled as an object. Of course, the SOAP extension of the SOAP message is not modified (for example, the SOAP extension of the SOAP message can only be run on the client or server. In this case, the receiver receives the same SOAP message as the SOAP extension is not running and the ASP.NET infrastructure can be reverse sequenced SOAP messages. In addition, if SOAP extensions are modified in a manner that cannot be implemented in a manner that cannot be implemented, the SOAP extension does not need to run on the client and run on the server.
Call the order of the SOAP extension method
Let's see when ASP.NET calls the SOAP extension method during the entire XML Web Services method call. The following steps assume that the SOAP extension is running on the client and running on the server. If the SOAP extension is running on the client and server, ASP.NET will ignore the steps running in any of these associated with the SOAP extension.
Client
1. The client is a method of calling the agent class.
2. Create a new instance of the SOAP extension on the client.
3. If this is the first time the SOAP extension is performed with this XML Web Services on the client, the GetInitializer method is called for the SOAP extension running on the client.
4. Call the Initialize method.
5. Call the Chainstream method.
6. Call the ProcessMessage method, set the SOAPMESSAGESTAGE to BeForeSerialize when calling.
7. ASP.NET on the client computer will sequence the parameter of the XML Web Services method to XML.
8. Call the ProcessMessage method, set the SOAPMESSAGESTAGE to AfterSerialize when calling.
9. ASP.NET on the client computer sends a SOAP message to the web server that carries the XML Web Services over the network.
Service-Terminal
1. ASP.NET on the web server receives the SOAP message.
2. Create a new instance of the SOAP extension on the web server.
3. On the web server, if this is the first time the server side uses the XML Web Services to execute the SOAP extension, call the GetInitializer method to the SOAP extension of the server. 4. Call the Initialize method.
5. Call the Chainstream method.
6. Call the ProcessMessage method, set the SOAPMESSAGESTAGE to BeforeDeserialize when calling.
7. ASP.NET in reverse sequence of parameters in XML.
8. Call the ProcessMessage method, set the SOAPMESSAGESTAGE to AfterDeserialize when calling.
9. ASP.NET creates a new instance of the class that implements the class of XML Web Services and calls the XML Web Services method while incoming the deserialized parameters. This object resides on the same computer as the web server.
10. The XML Web Services method executes its code and eventually sets the return value and any output parameters.
11. Call the ProcessMessage method, set the SOAPMESSAGESTAGE to BeForeSerialize when calling.
12. ASP.NET on the web server will return the value and the output parameter to XML.
13. Call the ProcessMessage method, set the SOAPMESSAGESTAGE to AfterSerialize when calling.
14. ASP.NET sends a SOAP response message back to the XML Web Services client via the network.
Client
1. ASP.NET on the client computer receives SOAP messages.
2. Call the ProcessMessage method and set the soapMessageStage when calling to BeforeDeserialize.
3. ASP.NET will turn XML inverse sequence to return values and any output parameters.
4. Call the ProcessMessage method, set the soapMessageStage when calling to AfterDeserialize.
5. ASP.NET passes the return value and any output parameters to an instance of the proxy class.
6. The client receives the return value and any output parameters.
We now explain the application of SOAP extensions in an example of .NET.
First, we write a SOAP EXTENSION program that is inherited to SOAPEXTension.
(TraceExtension.cs)
Using system;
Using system.Web.services;
Using system.web.services.protocols;
Using system.io;
Using system.net;
// define a soap extension That Tracs The Soap Request and SOAP
// Response for the XML Web Service Method The SOAP EXTENSION IS
// Applied To.
Public Class TraceExtension: SOAPEXTENSION
{
Stream oldstream;
Street newstream;
String filename;
// Save the stream representing the soap request or soap response Into
// a local memory buffer.
Public override stream chainstream (stream stream) {
OldStream = stream;
Newstream = new memorystream ();
Return newstream;
}
// when the soap extension is access for the first time, The XML Web // Service Method It is Applied To Is Accessed To Store
// Name Passed in, use the corresponding sopextensionattribute.
Public Override Object GetInitializer (LogicalMethodInfo MethodInfo, Soapextensionattribute Attribute)
{
Stream fs = new filestream ("D: //temp//a.txt", filemode.create);
StreamWriter Writer = New Streamwriter (FS);
Writer.writeline ("extension is ok");
//writer.flush ();
//fs.close ();
Writer.close ();
Return (TraceExtensionattribute) attribute; FileName;
}
// the soap extension WAS Configured to Run Using A Configuration FILE
// instead of an attribute applied to a specific XML Web Service
// Method.
Public Override Object GetInitializer (Type WebServiceType)
{
// Return A File name to log the trace information to, based on the
// Type.
Return WebServiceType.gettype (). Tostring () "Log";
}
// receive the file name store, getInitializer and store it IN A
// Member Variable for this specific instance.
Public Override Void Initialize (Object Initializer)
{
Stream Fs = New FileStream ("D: //TEMP//b.txt", filemode.create);
StreamWriter Writer = New Streamwriter (FS);
Writer.writeline ("Extension BB IS OK");
//writer.flush ();
//fs.close ();
FileName = (string) initializer; // Monitoring file is: c: /winnt/system32/system.runtimeType.log
Writer.writeline ("filename ==========" filename);
Writer.close ();
}
// if the soapMessagestage Is Such That The SoapRequest OR
// SOAPRESPONSE IS STILL in The SOAP FORMAT to Be Sent or Received,
// Save it out to a file.
Public Override Void ProcessMessage (SOAPMESSAGE Message) // Handling data. {
Switch (Message.Stage) {
Case SOAPMESSAGESTAGE.BEFORESERIALIZE:
Break;
Case SOAPMESSAGESTAGE.AFTERSERIALIZE:
WriteOutput (Message);
Break;
Case SOAPMESSAGESTAGE.BEFOREDSERIALIZE:
WriteInput (Message);
Break;
Case SOAPMESSAGESTAGE.AFTERDESERIALIZE:
Break;
DEFAULT:
Throw New Exception ("Invalid Stage");
}
}
Public void writeoutput (soapMessage message) {// can add a decision algorithm
Newstream.position = 0;
FILESTREAM FS = New FileStream (filename, filemode.Append,
FileAccess.write;
Streamwriter W = New StreamWriter (FS);
String soapstring = (message is soapserverMessage)? "soapResponse": "soapRequest";
w.writeline ("---- out ----" SOAPSTRING "AT" DATETIME.NOW);
w.writeLine ("Message =====" Message.MethodInfo.naMe);
w.flush ();
Copy (newstream, fs);
W. close ();
Newstream.position = 0;
Copy (Newstream, OldStream) and Copy (NEWSTREAM);
}
Public void writeinput (soapMessage message) {// can add an encryption algorithm
Copy (OldStream, NewStream);
FILESTREAM FS = New FileStream (filename, filemode.Append,
FileAccess.write;
Streamwriter W = New StreamWriter (FS);
String soapstring = (Message Is SOAPSERVERMESSAGE)?
"SoapRequest": "soapResponse";
w.writeline ("----- INT -------" SOAPSTRING
"AT" datetime.now;
w.flush ();
Newstream.position = 0;
Copy (newstream, fs);
W. close ();
Newstream.position = 0;
}
Void Copy (stream from, stream to)
{
TextReader Reader = New StreamReader (from);
TextWriter Writer = New Streamwriter (To);
Writer.writeline (Reader.ReadToend ());
Writer.flush ();
}
}
// Create A Soapextensionattribute for the soap extension That Can be // Applied to an XML Web Service Method.
[AttributeUSAG (AttributeTargets.method)]
Public Class TraceExtensionAttribute: soapextensionattribute {
Private string filename = "c: //log.txt";
PRIVATE INT Priority;
Public override type extensiontype {
Get {returnTen TypeOf (TraceExtension);
}
Public override int priority {
Get {return priority;}
Set {priority = value;}
}
Public string filename {
Get {
Return FileName;
}
SET {
FILENAME = VALUE;
}
}
}
We compile it into a DLL file, such as: CSC / T: library /out:c:/inetpub/wwwroot/bin/traceextension.dll TraceExtension.cs
Then we write a configuration file: Web.config:
soapextensiontypes>
WebServices>
configure>
Store web.config into the C: / INETPUB / WWWWROOT directory.
Finally, we can run Test.aspx again, we can find the data transmitted by the Client and Server end in the C: /WinntiType.log file. We can add the processMessage (SOAPMESSAGE) method in TraceExtension.cs. Upper encryption and decryption algorithm, change the data transmitted by Client-Server.
In short, SOAP extension is very useful in security confidentiality.