Asp. NET create Web Services design Guidelines

Source: Internet
Author: User
Tags abstract data structures header inheritance soap tostring web services wsdl
Asp.net|web|web Services | creating | Designing a simple XML Web service using ASP.net is relatively easy, however, the real power of XML Web services can only be realized when you have studied the infrastructure. XML Web services are built on the. NET Framework and the common language runtime. An XML Web service can take advantage of these technologies. For example, ASP. NET supports performance, state management, and validation, all of which can be used to construct XML Web services.

The infrastructure of an XML Web service is built to conform to industry standards such as SOAP, XML, and WSDL, and it allows clients of other platforms to interoperate with XML Web services. As long as a client can send a compliant SOAP message, based on a formatted service description, the client can invoke an XML Web service created using ASP.net, regardless of the platform on which the client exists.

When you construct an XML Web service using ASP.net, it automatically supports clients using SOAP, Http-get, and Http-post protocol communication. Even though Http-get and http-post support the use of URL-encoded variable name/variable value pairs to deliver messages, data types that support both protocols do not have rich data types that support the SOAP protocol. In soap, using XML to transfer data to an XML Web service or retrieving messages from an XML Web service, you can define complex data types using XSD schemas that support a rich set of data types. Developers using asp.net to construct an XML Web service do not have to explicitly define complex data types. They can construct only one Management class. Asp. NET processing defines a mapping class to an XSD schema and an instance of the mapped object to the XML data for transmission over the network.

It is important to note that XML Web services are not a substitute for DCOM, and we should say that XML Web services are a messaging infrastructure that spans the use of industry-standard platform communications.

Because ASP.net provides the infrastructure for working inside XML Web services, developers can focus on implementing the functionality of their particular XML Web services. Developing an XML Web service using ASP.net starts with the following three steps:

1. Create a file with an. asmx extension.

2. In this file, you use an instruction to declare an XML Web service.

3. Defines an XML Web service method that makes up the functionality of an XML Web service.

XML Web Services are a powerful technology for providing services that can be accessed via the Internet. The following recommendations will help you create an efficient XML Web service:

XML Web services support communication between synchronous and asynchronous clients and servers hosting XML Web services. In the case of synchronous communication, the client sends a request to the service to the service host server waiting for a response. This prevents the client from performing other actions while waiting for the result. However, asynchronous communication causes the client to continue to process other tasks while waiting for the appropriate time. The client responds to the results of the service request when available.

When you use the Web Service Description Language tool (Wsdl.exe) to create your proxy class, it produces standard, synchronous, and asynchronous versions of the methods in the class. An asynchronous version consists of two methods, called Begin and end. The Begin method is used to initialize the XML Web service, and the end method obtains the result.

Using asynchronous communication can improve system usage and avoid delays for clients when it waits for XML Web service results.

The following code example shows how to generate an asynchronous call to an XML Web service from a client application.

[C #]
<%@ Page language= "C #"%>
<%@ Import namespace= "System.Net"%>
<script language= "C #" runat= "Server"
void EnterBtn_Click (Object Src, EventArgs E)
{
Mymath.math Math = new Mymath.math ();
Call to Add XML Web service method asynchronously
And then wait for it to complete.
IAsyncResult result =
Math. BeginAdd (Convert.ToInt32 (Num1.text),
Convert.ToInt32 (Num2.text),
Null
NULL);
Wait for asynchronous call to complete.
Result. Asyncwaithandle.waitone ();
Complete the asynchronous call to Add XML Web service method.
Float total = Math. EndAdd (result);
Display results in a Label control.
Total.text = "Total:" + total. ToString ();
}
</script>
<body>
<form action= "Mathclient.aspx" runat=server>
<font face= "Verdana"
Enter the two numbers you want to add and then press
The total button.
<p>
Number 1:
<asp:textbox id= "Num1"
runat=server/>
+
Number 2:
<asp:textbox id= "Num2"
runat=server/>
=
<asp:button id= "Total_button"
text= "Total"

runat=server/>
<p>
<asp:label id= "Total" runat=server/>
</font>
</form>
</body>
[Visual Basic]
<%@ Page language= "VB"%>
<%@ Import namespace= "System.Net"%>
<script language= "VB" runat= "Server"
Sub EnterBtn_Click (Src as Object, E as EventArgs)
Dim Math as New mymath.math ()
' Call to Add XML Web service method asynchronously
' And then wait for it to complete.
Dim result as IAsyncResult = _
Math. BeginAdd (Convert.ToInt32 (Num1.text), _
Convert.ToInt32 (Num2.text), _
Nothing, _
Nothing)

' Wait for asynchronous call to complete.
Result. Asyncwaithandle.waitone ()
' Complete the asynchronous call to Add XML Web service method.
Dim addtotal as single = Math. EndAdd (Result)
"Display results in a" Label control.
Total.text = "Total:" & AddTotal. ToString ()
End Sub
</script>
<body>
<form action= "Mathclient.aspx" runat=server>
<font face= "Verdana"
Enter the two numbers you want to add and then press
The total button.
<p>
Number 1:
<asp:textbox id= "Num1"
runat=server/>
+
Number 2:
<asp:textbox id= "Num2"
runat=server/>
=
<asp:button id= "Total_button"
text= "Total"

runat=server/>
<p>
<asp:label id= "Total" runat=server/>
</font>
</form>
</body>
For more information about asynchronous communication, see "Communicating asynchronously with XML Web Services" later in this page.
The creation of many service requests over the Internet can affect the performance of client applications. When designing your XML Web services, you can effectively leverage service requests by creating a way to centralize information about them. For example, suppose you have an XML Web service that retrieves information for a book. We can create a way to return all the information in a service request instead of a separate method for retrieving titles, authors, and publishers. Sending chunks of information at once is more efficient than sending small chunks of information over multiple times.

The following code example explains how to organize information into a single XML Web service method.

[C #]
<%@ WebService language= "C #" class= "DataService"%>
Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Web.Services;
public class DataService {
[WebMethod]
Public DataSet GetTitleAuthors () {
SqlConnection myconnection = new SqlConnection ("Persist Security info=false;integrated Security=sspi;server=localhost ;d atabase=pubs ");
SqlDataAdapter myCommand1 = new SqlDataAdapter ("select * from Authors", MyConnection);
SqlDataAdapter myCommand2 = new SqlDataAdapter ("select * from Titles", MyConnection);
DataSet ds = new DataSet ();
MyCommand1.Fill (ds, "Authors");
MyCommand2.Fill (ds, "Titles");
return DS;
}
}
[Visual Basic]
<%@ WebService language= "VB" class= "DataService"%>
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Public Class DataService
<WebMethod> _
Public Function GetTitleAuthors () as DataSet
Dim MyConnection as New SqlConnection ("Persist Security info=false;integrated security=sspi;server=localhost;database =pubs ")
Dim MyCommand1 as New SqlDataAdapter ("select * from Authors", MyConnection)
Dim MyCommand2 as New SqlDataAdapter ("select * from Titles", MyConnection)
Dim DS as New DataSet ()
MyCommand1.Fill (ds, "Authors")
MyCommand2.Fill (ds, "Titles")
Return DS
End Function
End Class
When designing your XML Web service, be sure to use standard object-oriented programming operations. Use encapsulation to hide implementation details. For more complex XML Web services, you can use inheritance and polymorphism to reuse code and simplify your design.

The following code example shows how to use inheritance to create an XML Web service that performs mathematical calculations.

[C #]
<%@ WebService language= "C #" class= "Add"%>
Using System;
Using System.Web.Services;
Abstract public class Mathservice:webservice
{
[WebMethod]
Abstract public float calculatetotal (float A, float b);
}
public class Add:mathservice
{
[WebMethod]
Override public float calculatetotal (float A, float b)
{
return a + B;
}
}
public class Subtract:mathservice
{
[WebMethod]
Override public float calculatetotal (float A, float b)
{
return a-b;
}
}
public class Multiply:mathservice
{
[WebMethod]
Override public float calculatetotal (float A, float b)
{
return a * b;
}
}
public class Divide:mathservice
{
[WebMethod]
Override public float calculatetotal (float A, float b)
{
if (b==0)
return-1;
Else
return a/b;
}
}
[Visual Basic]
<%@ WebService language= "VB" class= "Add"%>
Imports System
Imports System.Web.Services
MustInherit Public Class mathservice:inherits WebService
<WebMethod> _
Public MustOverride Function CalculateTotal (A as single, _
B as Single
End Class
Public Class add:inherits MathService
<WebMethod> public Overrides Function CalculateTotal (A as only, B as single)
Return a + b
End Function
End Class
Public Class subtract:inherits MathService
<WebMethod> public Overrides Function CalculateTotal (A as only, B as single)
Return A-b
End Function
End Class
Public Class multiply:inherits MathService
<WebMethod> public Overrides Function CalculateTotal (A as only, B as single)
return a * b
End Function
End Class
Public Class divide:inherits MathService
<WebMethod> public Overrides Function CalculateTotal (A as only, B as single)
If B = 0 Then
Return-1
Else
Return A/b
End If
End Function
End Class

Use output buffering to improve the performance of your XML Web service. When the output buffer is turned on, the result of the service request is saved in the output buffer for a specified amount of time. If a similar XML Web service request is generated, the result can be obtained from the buffer without recalculation. This improves the feedback time for XML Web services by reducing the processing required by the XML Web service server. Caching can be performed on both the client and the server. The Duration property allows you to specify the time that the cache saves XML Web service output.

The instructions for using output caching on the client are:

<%@ OutputCache duration= "60"%>
The following code example shows how to use the Duration property on a client application to specify an output high-speed buffer of 60 seconds.

[C #]
<%@ Page language= "C #"%>
<%@ Import namespace= "System.Net"%>
<%@ OutputCache duration= "No" varybyparam= "None"%>
<script language= "C #" runat= "Server"
void EnterBtn_Click (Object Src, EventArgs e)
{
Mymath.math Math = new Mymath.math ();
Call the XML Web service.
Float total = Math. ADD (Convert.ToInt32 (Num1.text),
Convert.ToInt32 (Num2.text));
Display the results in a Label control.
Total.text = "Total:" + total. ToString ();
}
</script>
<body>
<form action= "Mathclient.aspx" runat=server>
<font face= "Verdana"
Enter the two numbers you want to add and press
The total button.
<p>
Number 1:
<asp:textbox id= "Num1" runat=server/>
+ Number 2:
<asp:textbox id= "Num2" runat=server/>
= <asp:button id= "Total_button" text= "Total" runat=server/>
<p>
<asp:label id= "Total" runat=server/>
</font>
</form>
</body>
[Visual Basic]
<%@ Page language= "VB"%>
<%@ Import namespace= "System.Net"%>
<%@ OutputCache duration= "No" varybyparam= "None"%>
<script language= "VB" runat= "Server"
Sub EnterBtn_Click (SRC as Object, e as EventArgs)
Dim Math as New mymath.math ()
' Call the XML Web service.
Dim addtotal as single = Math. ADD (Convert.ToInt32 (Num1.text), Convert.ToInt32 (Num2.text))
' Display the results in a Label control.
Total.text = "Total:" & AddTotal. ToString ()
End Sub
</script>
<body>
<form action= "Mathclient.aspx" runat=server>
<font face= "Verdana"
Enter the two numbers you want to add and press
The total button.
<p>
Number 1:
<asp:textbox id= "Num1" runat=server/>
+
Number 2:
<asp:textbox id= "Num2" runat=server/>
= <asp:button id= "Total_button" text= "Total" runat=server/>
<p>
<asp:label id= "Total" runat=server/>
</font>
</form>
</body>
You can also use the CacheDuration property of the WebMethod property class to allow high-speed buffering on the server. The following code example shows how to use the CacheDuration property on an XML Web service method to specify an output high-speed buffer of 60 seconds.

[C #]
<%@ WebService language= "C #" class= "MathService"%>
Using System;
Using System.Web.Services;
public class Mathservice:webservice {
[WebMethod (CACHEDURATION=60)]
public float ADD (float A, float b)
{
return a + B;
}
[WebMethod (CACHEDURATION=60)]
public float subtract (float A, float b)
{
return a-b;
}
[WebMethod (CACHEDURATION=60)]
public float Multiply (float A, float b)
{
return a * b;
}
[WebMethod (CACHEDURATION=60)]
public float Divide (float A, float b)
{
if (b==0) return-1;
return a/b;
}
}
[Visual Basic]
<%@ WebService language= "VB" class= "MathService"%>
Imports System
Imports System.Web.Services
Public Class MathService
Inherits WebService
<webmethod (cacheduration: = 60) > _
Public Function Add (a as only, B as single)
Return a + b
End Function

<webmethod (cacheduration: = 60) > _
Public Function subtract (a as only, B as single)
Return A-b
End Function

<webmethod (cacheduration: = 60) > _
Public Function Multiply (a as only, B as single)
return a * b
End Function

<webmethod (cacheduration: = 60) > _
Public Function Divide (a as only, B as single)
If B = 0 Then
Return-1
End If
Return A/b
End Function
End Class
When designing your XML Web service, try to follow the structure of how to format the schema.

The XML Web service uses SOAP as the primary Routing and serialization Protocol. A SOAP message consists of an optional header body and a message body. The header section contains information that can be processed by the Web server architecture. SOAP does not define any headers. The Message body section contains information that is processed by the application, such as parameters or return values for an XML Web service.

Provides documents for your XML Web service, such as a static HTML file that describes the operations and data structures of your service. Also includes examples of how to use this XML Web service. Do not rely on the service description or service help page as your only document.

Related Article

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.