Click here to Skip to main content
Click here to Skip to main content

How to Call Microsoft .Net web services from .Net consumers, and Non .Net consumers

By , 17 May 2007
Rate this:
Please Sign up or sign in to vote.

When I was first introduced with Microsoft .Net Web services, it was quite tricky for me to know on how I can utilize web services that implemented in .Net languages such as C#, VB.Net, in ASP code, and the different web protocols to communicate always confused me.

This article will definitely help beginners, who just step in to Web Services world.

Assumptions:

Reader must know about the architecture of Web services, and how to create web service through Microsoft Visual Studio .Net. In addition, reader must have basic knowledge of XML.

Introduction

Overview:

Web services allow access to software components through standard protocols such as HTTP and SMTP. Using the Internet and XML, we can now create software components that communicate with others, regardless of language, platform.

Comparison between DCOM and Web services:

DCOM and Web services are to make distributed components, but main benefit of Web services as compare to DCOM (AKA COM over wire) is that any application on any platform can access the web services as long as it uses standard web protocols, and understands the XML encoded messages.

Web service clients (AKA consumer) communicate with the web services, through standard protocols such as HTTP Post, HTTP Get, and SOAP. We demonstrate next how to build client applications that utilize each of these protocols.

Description

To understand the concept, we will be creating one simple Web Service Provider first, and then, by using this web service, we will see how it can be consume.

Web Service Provider

Web Services providers implement web services and advertise them so that the clients can discover and make use of the services. Because web services run on top of HTTP, there must be a web server application of some sort on the machine that hosts the web services. This web server application can be Microsoft Internet Information Services (IIS), Apache, or any other program that can understand and process the HTTP protocol. In our examples, we use Microsoft IIS, since that is the only web server currently supported by .NET. Later on, we will see how it can be consume.

Below, we describe code for one of the simplest web service, stored in "Service.asmx" file, which containing two web methods:

Method Name

Parameters

Return Type

Comments

HelloWorld

NONE

String

Return "Hello World"

HelloWorldWithCustomMessage

@s_Msg – string

String

Append parameter string with "Hello World" and return.

Of course, access modifier for all web method will be public.

Code Snippet

 
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "<a href="http://tempuri.org/">http://tempuri.org/</a>")]
public class Service : System.Web.Services.WebService
{
    public Service () {
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

<pre class="MsoNormal" style="MARGIN: 0in 0in 0pt">    [WebMethod]
    public string HelloWorldWithCustomMessage(string s_Msg)
    {
        return "Hello World " + s_Msg;
    }
}

NOTE: I assumed that IIS server is accessible through http://localhost/ link, and we deploy above created web service under virtual directory called "HelloWorldWS".

Web Services Consumers

In above section, we created Web Service Provider successfully, let see how this web service can use by web clients.

HTTP Get Consumer (Web Browser):

This consumer is the simplest one. If we point web browser at the web service URL (http://localhost/HelloWorldWS/Service.asmx), it will give us a list of supported Web methods.

<formulas></formulas>

Sample screenshot

To find out more about these methods, click one of them. This brings up a default web service consumer. This consumer, auto generated with reflection, is great for testing your web services' methods. It uses the HTTP GET protocol to communicate with the web service. This consumer features a form that lets you test the method (see figure), as well as descriptions of how to access the method via SOAP, HTTP GET, or HTTP POST (We can use this information as reference, when we call web service through Non .Net consumer).

Sample screenshot

(Figure – HelloWorldWithCustomMessage Method Testing)

Very easy to consume… yeaa?

.Net Consumers

HTTP Post Protocol:

In the above section, we have seen that creating HTTP Get Consumer is just hitting the URL of the web services. Next, we will see how to write consumer code that can use HTTP Post and SOAP to access web services.

Note: We will be using C# code to consume web service.

Steps to utilize Web Service:

I) Generate web Service proxy code

Microsoft.net SDK rich with various tools to simplify the process of creating or consuming web services. One of the most important tool that use with web service is WSDL.EXE. WSDL tool takes WSDL file as an input, and create proxy for the consumer.

Below is the exact command that we use to create Proxy file for our web service "HelloWorldWS/Service.asmx"

Wsdl /l:cs /protocol:HTTPPost http://localhost/HelloWorldWS/Service.asmx?wsdl


/l:cs – tells the language type
/protocol:HTTPPost – tells protocol type; we can also use /protocol:HTTPGet or /protocol:SOAP parameters.
URL – A location of WSDL file.

It will produce Service.cs file that contain proxy code.

About proxy in brief: Proxy source code similar to the way IDL compilers generate source file for DCOM Proxy.

NOTE: If you look at this generated C# file, you will see that it contains a proxy class Service that derives from HttpPostClientProtocol class. If you use the /protocol:HttpGet or /protocol:SOAP parameters, then the Service derives from either the HttpGetClientProtocol or SoapHttpClientProtocol class, respectively.

II) Once we created Proxy, our next job is to utilize proxy. To utilize Proxy, first I compile proxy, create DLL file, and refer DLL when I will compile consumer.



Create DLL file

Csc /target:library Service.cs

It will create Service.dll

Write consumer code

I wrote simple one:

Sample screenshot


Compile consumer with the DLL reference

csc /r:Service.dll CallHelloWorldWS_SOAP_Using_Proxy.cs

Execute CallHelloworldWS_SOAP_Using_Proxy.exe

csc CallhelloWorldws_Soap_Using_Proxy

Output: Hello World

You might be thinking, why so many steps are required to follow when we want to utilize web service through consumer code.

Practically speaking, these steps required when the consumer code is not a .Net language. But if you want to utilize it for any of Microsoft .Net languages (VB.net, C#, Managed C++, Jscript) and you have Microsoft Visual Studio .Net IDE then you just need to discover and add web service reference. Rest of the task will be taken care by VS.Net IDE - all right, after reading this sentence, I believe 90% reader will appreciate VS.Net IDE, and will not run away from this article Smile | :) .

Non-.Net Consumers

This section shows how to develop non-.NET web service consumers using HTTP GET, HTTP POST, and SOAP protocols.

We have used ASP Non-.Net Language, and those who are interesting to call web service from other Non-.Net language, such as PERL, they must need to find substitute of XMLHTTP component.

HTTP Get Protocol:

Idea is to use XMLHTTP component to call web page/code available over the Internet, and return result to the caller.

Comments: We can also use ASPTear component instead of XMLHTTP, which is available free of charge.

Below code snippet is self-explanatory:

<%

Dim o_XmlhttpCaller




' Create Object of MSXml2.XMLHTTP

Set o_XmlhttpCaller = Server.CreateObject("Msxml2.XMLHTTP")

' Check whether object created successfully.

If ( o_XmlhttpCaller is nothing ) Then

Response.Write("<font color=red size=-1>Unable to create Object - 
Type: Msxml2.XMLHTTP<BR></font>")




Response.Write("Solution: Install MSXML 4.0")

End If

'Open method will take three arguments

'@Param1

'Method - POST or GET

'@Param2

'URL - Uniform Resource Locator 

' It must be a valid URL (check by visiting through Iexplore or any browser)

'@Params3

'Async - If true then the call would be asynchronous, else Synchronous.

o_XmlhttpCaller.open "GET","http://localhost/WSHelloWorld/Service.asmx/
HelloWorldWithCustomMessage?s_msg= Hope you like this article.", False

'Make call to the web service. 

o_XmlhttpCaller.send

'Okay, play return data according to your need.

' I response back to browser as it is.

Response.Write(o_XmlhttpCaller.responseText)

' Time to clean the mess manually:-/ Ahh... can we request Microsoft to 
build GC for ASP? :)

Set o_XmlhttpCaller = nothing

%> 
HTTP Post Protocol:

Idea of implementation for HTTP POST and HTTP Get Protocol will remain the same, except few changes done in above code.

Here is the changed code lines for you:

'@Param1

'Method - POST or GET

' POST can be use when we do not want to send data as form submission

'@Param2

'URL - Uniform Resource Locator 

' It must be a valid URL (check by visiting through Iexplore or any browser)

'@Params3

'Async - If true then the call would be asynchronous, else Synchronous.

'This time we are not passing query string with URL.

o_XmlhttpCaller.open "POST","http://localhost/WSHelloWorld/Service.asmx/
HelloWorldWithCustomMessage", False

' XMLHTTP by default pass data in the form of XML, 

' and it require to set Content-Type = "application/x-www-form-urlencoded".

o_XmlhttpCaller.setRequestHeader "Content-Type", 
"application/x-www-form-urlencoded"
'Make call, and pass form value with variable name that expected by the 
web service(If any).

' NOTE: Variable Name must match with web method parameter!!

o_XmlhttpCaller.send("s_Msg= I hope this article will help .Net 
Champions somewhere:-)")

SOAP Protocol:

As we did above, using SOAP Protocol is also the same, but here we pass structured message - SOAP Message.

If you recall, which testing "HelloWorldWithCustomMessage" method through Web Browser, we saw SOAP message format that expecting to communicate with the Web service. Same SOAP format has used in below code:

'This line is different than HTTP Post code 

'We are not telling which action require to call , because the SOAP header 
(see below) contain this information.

o_XmlhttpCaller.open "POST",<a href="http://localhost/WSHelloWorld/Service.asmx">http://localhost/WSHelloWorld/Service.asmx</a>, 
False

'This time we will set content-type to XML because, SOAP message in the 
form of XML.

o_XmlhttpCaller.setRequestHeader "Content-Type", "text/xml"


'Here is what we are setting soap action that require to call

o_XmlhttpCaller.setRequestHeader "SOAPAction","http://tempuri.org/
HelloWorldWithCustomMessage"
'Prepare soap message

Dim soapMessage 

soapMessage = "<soap:Envelope 
xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance%22">http://www.w3.org/2001/XMLSchema-instance"</a> 
xmlns:xsd="<a href="http://www.w3.org/2001/XMLSchema%22">http://www.w3.org/2001/XMLSchema"</a> 
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">


Conclusion

In this article, we have seen different Protocols available to consume Web Service, and how we call Web Service from .Net, NON-.Net Language.

If you learn anything from this article, please vote.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

codebased
Web Developer
United States United States
I'm working as Analyst Programmer for e.Bit, Sydney and I like Object Oriented Programming languages.
 
Email: Amit.m@programmer.net

Comments and Discussions

 
GeneralCalling Web services without .asmx PinmemberArulManoj19-Jan-09 17:42 
GeneralThanks ! PinmemberFletcher Dunton5-Nov-08 9:45 
Questionhow to call method from web page? PinmemberPravat Maskey6-Sep-08 23:21 
GeneralWS Permissions Pinmemberthund3rstruck18-May-07 4:21 
AnswerRe: WS Permissions PinmemberPrem Malhotra9-Jul-07 22:32 
GeneralNice article!! PinmemberPrasadGVL12-Feb-06 18:40 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 17 May 2007
Article Copyright 2006 by codebased
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid