Click here to Skip to main content
15,861,168 members
Articles / Web Development / IIS

ASP.NET Web Service

Rate me:
Please Sign up or sign in to vote.
4.70/5 (74 votes)
7 Jul 2001CPOL4 min read 1.3M   20.1K   176   63
Tutorial on Creating ASP.NET Web Service

Introduction

We can now use ASP.NET to create Web Service that is based on industrial standards included XML, SOAP and WSDL.

ASP.NET Web Services support clients using HTTP-POST, HTTP-GET and SOAP protocols to invoke methods exposed, depends on your specific requirement you choose one method over the others. The main difference between HTTP-GET or HTTP-POST and SOAP is the data types supported by SOAP is much richer because SOAP used XSD schema to represent complex data types.

Here are samples codes I use to test the building of ASP.NET Web Service:

Step 1: Create the ASP.NET Web Service Source File

ASP.NET Web Service file name has extension asmx and my file is named MyWebService.asmx, source is listed as follows:

File: MyWebService.asmx

C#
<%@ WebService Language="C#" class="MyClass" %>

using  System.Web.Services ;

public class MyClass
{
        [WebMethod()]
        public  int Add ( int a,  int  b)
        {
                return a + b ;        
        }
}

The page directive WebService is required and class is the name of the .NET Class to expose the Web Service, each method exposes as Web Service Class Method need to have a declarative attribute statement [WebMethod()] in front of it. Here the .NET Class implementation is included in the same file with ASP.NET Web Service file but it is not mandatory and we can choose to include an external .NET Assembly to implement the service as the following example:

File: MyWebService2.asmx

C#
<%@ WebService Language="C#"  class="MyWebService.MyStringReverse, MyWebServiceImpl" %>

The file MyWebService2.asmx is referencing another .NET Assembly MyWebServiceImpl which is located under the /bin ASP.NET Application sub-folder (note that the default location for Assemblies in ASP.NET is /bin sub-folder under each ASP.NET Applications). The source of .NET Assembly MyWebServiceImpl is written by C# and is listed as follows:

File: MyWebServiceImpl.cs

C#
namespace MyWebService
 {
 	using System ;
using System.Web.Services ;

public class MyStringReverse: WebService
{
        		[WebMethod(Description="Reverse String")]
        		public  String ReverseString ( String InString )
        		{
                		// Check null String
                		if ( InString == null )  return null ;
                        
                		Int32 intSize = InString.Length ;
                	char[] arrayInString = InString.ToCharArray() ;
            	    	char[] arrayOutString = new char[intSize] ;
                
                        for (Int32 i = 0 ; i < intSize ; ++i) 
                        		arrayOutString[i] = arrayInString[intSize-i-1] ;
                        
                	return new String(arrayOutString) ;        
        		}
 	}
}

To create the Assembly, you can use the following command:

C:\>CSC   /t:library    /out:bin/MyWebServiceImpl.dll   MyWebServiceImpl.cs 

The following sections I will continue use MyWebService.asmx as my experimental Web Service.

Step 2: Create the ASP.NET Web Service Clients

There are many ways to consume Web Services and have three examples. The first one uses HTTP-POST protocol and it has advantage to coexist with today’s application quite well and use HTTP-GET is similar and I let reader to try it. The second one uses SOAP Proxy Client Object generated by WSDL utility and it provides programmers with their familiar object modal that they call methods provided by the generated Proxy Interface. The final one uses SOAP standard request message and it parses SOAP response message with the help of XMLHTTP COM object that is installed by Microsoft XML Parser 3.0.

Client use HTTP-POST Method

The example is an ASP.NET page TestWebService.aspx and source listing as follows:

File: TestWebService.aspx

HTML
<html>

<body>
<form action="http://localhost/ASP.NET/MyWebService.asmx/Add"  method="POST">

        <input name="a"></input>
        <input name="b"></input>
        
        <input type="submit" value="Enter"> </input>
</form>

</body>
</html>

The ASP page accepts parameters from browser and calls the Add method of the Web Service MyWebService via the HTTP-POST protocol, the result will be XML message and need further parsing by the client application. To parse the response, client can use either Java XML parser in applet or use IE5’s DOM Object.

The following is an example of XML response when parameters a=1, b=2 are inputted:

HTML
<?xml version="1.0" encoding="utf-8" ?>
<int xmlns="http://tempuri.org/">3</int>

Client use WSDL Generated Proxy Object

If your client will be Windows applications or ASP.NET applications, you can use WSDL.EXE utility to created standard .NET Assemble to provide Proxy Class for your clients.

Here are steps you can follow and try:

Use WSDL.EXE utility to create the Proxy Class source file in any language you have chosen and here I use C# and command as follows:

C:\>wsdl    /language:C#     /out:MyProxyClass.cs    http://localhost/ASP.NET/MyWebService.asmx

MyProxyClass.cs is generated and source listing as follows:

File: MyProxyClass.cs

C#
//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a tool.
//     Runtime Version: 1.0.2914.16
//
//     Changes to this file may cause incorrect behavior and will be lost if 
//     the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------

// 
// This source code was auto-generated by wsdl, Version=1.0.2914.16.
// 
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.Web.Services;

[System.Web.Services.WebServiceBindingAttribute(Name="MyClassSoap", Namespace="http://tempuri.org/")]
public class MyClass : System.Web.Services.Protocols.SoapHttpClientProtocol {
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public MyClass() {
        this.Url = "http://localhost/ASP.NET/MyWebService.asmx";
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Add", 

Use=System.Web.Services.Description.SoapBindingUse.Literal, 

ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    public int Add(int a, int b) {
        object[] results = this.Invoke("Add", new object[] {
                    a,
                    b});
        return ((int)(results[0]));
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public System.IAsyncResult BeginAdd(int a, int b, System.AsyncCallback callback, object asyncState) {
        return this.BeginInvoke("Add", new object[] {
                    a,
                    b}, callback, asyncState);
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public int EndAdd(System.IAsyncResult asyncResult) {
        object[] results = this.EndInvoke(asyncResult);
        return ((int)(results[0]));
    }
}

Then we need to create the .NET Assembly for used by clients:

C:\> csc /t:library MyProxyClass.cs

The above command will compile the source and create MyProxyClass.dll library file.

I use ASP to depict how to use the proxy object and the file is TestWebServiceWithProxy.aspx source listing as follows:

File: TestWebServiceWithProxy.aspx

C#
<%@ page language="C#" %>
<html>
<script runat="server">
        void btn_click(Object source, EventArgs e)
        {
                MyClass mycls = new MyClass() ;
                int x = Int32.Parse(a.Text) ;
                int y = Int32.Parse(b.Text);
                
                Message.Text = mycls.Add( x, y).ToString() ;
        }
</script>

<body>
<form Action = "TestWebServiceWithProxy.aspx" runat="server">
        <asp:TextBox id="a" runat="server" />
        <asp:TextBox id="b" runat="server" />
        <asp:button id=btn OnClick="btn_click" Text="Enter" runat="server" />
        <p><asp:label id="Message" runat="server" /></P>
</form>
</body>
</html>

Client use XMLHTTP to call Web service via SOAP

To fully explore the SOAP capability, you may choose to call your ASP.NET Web Service via SOAP core protocol and here I provide another example for reference.

To test the ASP.NET service with SOAP protocol, I create an ASP client file TestWebServiceByXML.asp and its source is listed as follows:

File: TestWebServiceByXML.asp

HTML
<html>
<body>
<script language="jscript">
        function btn_click (a, b)
        {
                var xmlObj = new ActiveXObject("Msxml2.DOMDocument") ;
                var sXml  = "<?xml version=\"1.0\" ?>" ;
                      sXml += "<soap:Envelope "
                      sXml += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " ;
                      sXml += "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " ;
                      sXml += "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" ;
                      sXml += "<soap:Body>" ;
                      sXml += "<Add xmlns=\"http://tempuri.org/\">" ;
                      sXml = sXml + "<a>" + a.value  + "</a>" ;
                      sXml = sXml + "<b>" + b.value  + "</b>" ;                      
                      sXml += "</Add></soap:Body></soap:Envelope>"
                
	   // Try to parse the XML string into DOM object 
                xmlObj.loadXML(sXml) ;
                
	   //To see the validated XML string is well-formed 
                XmlRequest.innerText =  xmlObj.xml  ;
                
                var xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP") ;
                xmlHTTP.Open ( "Post", "http://localhost/ASP.NET/MyWebService.asmx", false) ;
                xmlHTTP.setRequestHeader("SOAPAction", "http://tempuri.org/Add") ;
                xmlHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8" ) ;
                xmlHTTP.Send(xmlObj.xml) ;
                MyResult.innerText =  xmlHTTP.responseText ;
                
                var xmlResponse = xmlHTTP.responseXML ;
                answer.innerText = xmlResponse.selectSingleNode("soap:Envelope/soap:Body/AddResponse/AddResult").text ;
        }
</script>

<form>
        <p>Please input a:<input id="a" name="a"></input></p>
        <p>Please input b:<input id="b" name="b"></input></p>
        <p>
        <input type="button" id="btn"  value="Enter" 
                onclick="jscript:btn_click(a, b)"></input>
        </p>
        <p>Answer is <span id="answer"></span></p>
        <hr></hr>
        <p>Request:</p>
        <span id="XmlRequest"></span>
        <p>Response:</p>
        <span id="MyResult"></span>
        
</form>

</body>
</html>

Here I installed Microsoft XML Parser 3.0 in my client machine that give me the XMLHTTP and DOM COM objects to test my application.

Summary

There are many difference implementations for SOAP Service but the standard is there and we can start to build some useful applications on it. Although ASP.NET or SOAP web services have many nice features, if you want to consume the exposed Web Services in you clients, please make sure you have the latest libraries installed because standards continue evolving and all vendors try their best achieve the edge in such open standards war.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Software Force
Hong Kong Hong Kong
I am always interested in finding innovative ways for building better applications and founded a technology company since 2003. Welcome to exchange any idea with you and if I am not too busy before deadline of projects, I will reply your emails. Also, if you willing to pay for consulting works and customized software development, you can leave me message.

Comments and Discussions

 
GeneralThis is a great article Pin
Member 109933346-Aug-14 3:35
Member 109933346-Aug-14 3:35 
GeneralMy vote of 5 Pin
ahmed rageeb26-May-13 19:31
ahmed rageeb26-May-13 19:31 
Questionhow .net webservices stores data which are coming from android(data sended using HttpPost method) Pin
Member 986794030-Mar-13 9:28
Member 986794030-Mar-13 9:28 
GeneralMy vote of 5 Pin
Azziet28-Feb-13 23:21
Azziet28-Feb-13 23:21 
Questionnot very clear Pin
serpiccio8-Feb-13 7:45
serpiccio8-Feb-13 7:45 
SuggestionAll About Web Service For Beginner Pin
etechpulse28-Sep-12 7:42
etechpulse28-Sep-12 7:42 
GeneralMy vote of 4 Pin
Unareshraju19-Feb-12 18:29
Unareshraju19-Feb-12 18:29 
QuestionHow to get WSDL methods? Pin
srajasekaranmsc8914-Feb-12 0:18
srajasekaranmsc8914-Feb-12 0:18 
QuestionWSDL with ASP.net Pin
elaiyaraja.r14-Feb-12 0:06
elaiyaraja.r14-Feb-12 0:06 
Questiongreat article............. Pin
Ajendra Prasad31-Jan-12 21:22
Ajendra Prasad31-Jan-12 21:22 
GeneralMy vote of 1 Pin
Jyoti Bhardwaj7-Nov-11 1:15
Jyoti Bhardwaj7-Nov-11 1:15 
GeneralMy vote of 1 Pin
Jyoti Bhardwaj7-Nov-11 1:15
Jyoti Bhardwaj7-Nov-11 1:15 
GeneralMy vote of 2 Pin
Rajesh Duraisamy1-Aug-11 0:21
Rajesh Duraisamy1-Aug-11 0:21 
GeneralRe: My vote of 2 Pin
Member 85894308-Feb-12 19:38
Member 85894308-Feb-12 19:38 
GeneralMy vote of 5 Pin
gaurav0729-Jul-11 0:01
gaurav0729-Jul-11 0:01 
GeneralMy vote of 4 Pin
Anupam Singh23-Jun-11 22:46
Anupam Singh23-Jun-11 22:46 
GeneralMy vote of 5 Pin
swapnilsonawane12323-Jun-11 0:33
swapnilsonawane12323-Jun-11 0:33 
GeneralMy vote of 5 Pin
Monjurul Habib12-Feb-11 6:58
professionalMonjurul Habib12-Feb-11 6:58 
GeneralMy vote of 2 Pin
AmitDas11119-Jul-10 2:25
AmitDas11119-Jul-10 2:25 
GeneralMy vote of 1 Pin
Member 690977614-Jun-10 23:52
Member 690977614-Jun-10 23:52 
QuestionRead web service url from text file Pin
jymitra16-May-10 19:53
jymitra16-May-10 19:53 
AnswerRe: Read web service url from text file Pin
foluis29-Mar-11 5:04
foluis29-Mar-11 5:04 
QuestionWeb Service - Should I use DataSet to read and write xml files ? Pin
pcphuc6-Dec-09 17:27
pcphuc6-Dec-09 17:27 
Generalcalling webservice from C# code : please help Pin
amit_ambitions21-Oct-09 22:27
amit_ambitions21-Oct-09 22:27 
GeneralAccessing wsdl web service with c# client via proxi Pin
qwerty5316-Dec-08 3:52
qwerty5316-Dec-08 3:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.