|
HTML clipboard
<%@ WebService Language="C#" class="HelloService" %>
using System;
using System.Web.Services;
[WebService(Namespace="http: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:
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:
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>
|