How to write your first web service in C# PDF Print E-mail
User Rating: / 0
PoorBest 
Monday, 09 March 2009
HTML clipboard

Open your favourite text editor, place the following codes into it and name it as hello.asmx.

<%@ WebService Language="C#" class="HelloService" %>
using System;
using System.Web.Services;
[WebService(Namespace="http://www.csharpfriends.com/webservices/")]class HelloService {
[WebMethod]
public string SayHello() {
return "Hello World";
}
}

To begin, you must special that it is a web service by using the WebService directive. In the directive specify the language you use as well. In this case, it is C#.

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

After the directive, put any namespaces that you will be using into the file by using the using keyword. Remember to import the System.Web.Services namespace here by adding the line "using System.Web.Services"

[WebService(Namespace="http://www.csharpfriends.com/webservices/")]

The above line is optional. It specify the namespace used so to prevent name crashes. If it isn't specified, a default one "http://tempuri.org" will be added automatically. However, it is suggested that you add this line for a professional and public web service.

Finally, expose any method in your class as web method by adding the [WebMethod] attribute right above your method.

You may now test your web service by opening your favourite browser (mostly IE, since I never test it in netscape). Say, if you put your web service in your local web server, you may like to access it by http://localhost/hello.asmx. By clicking on the link SayHello and then on the next page Invoke, you will in return get an XML packet as the response of the web service.

To consume the web service, you must first create a proxy class by using the following command (in your command prompt):

wsdl "http://localhost/hello.asmx" /out:hello.cs

After that, you will find a file hello.cs in the current directory created by the wsdl utility, which come with the .NET Framework. To consume it, you must compile it as a DLL:

csc hello.cs /t:library /out:hello.dll /r:System.Web.Service.dll /r:System.Xml.dll

Remember to reference the System.Web.Service.dll and System.Xml.dll libraries.

Put it into the /bin directory in your web server. Finally you can consume the web service through the following simple ASP.NET code:

<%@ Page Language="C#" %>
<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs e) {
    HelloService hs = new HelloService();
    Label1.Text = hs.SayHello();
}
</script>
<html>
<head>
<title>Hello WebService</title>
</head>
<body>
<asp:Label id="Label1" runat="server" />
</body>
</html>

Last Updated ( Monday, 09 March 2009 )
 
< Prev   Next >
School Joomla Templates and Joomla Tutorials