Writing a simple Web Service takes only a few minutes, and can be accomplished in any text editor. The service we will build in this section, MathService, exposes methods for adding, subtracting, dividing, and multiplying two numbers.
At the top of the page is a directive that identifies the file as a Web Service in addition to specifying the language for the service (C#, in this case):
<div class="code"><pre>
<%@ WebService Language="C#" %>
</pre></div>
<p>
In this same file, we define a class that encapsulates the functionality of our service. This class should be public, and inherit from the <b>WebService</b> base
class. Each method that will be exposed from the service is flagged with a [WebMethod] custom attribute in front of it. Without this
attribute, the method will not be exposed from the service. This is sometimes useful for hiding implementation details called by public
Web Service methods, or for the case where the WebService class is also used in local applications (a local application can use any
public class, but only [WebMethod] classes will be remotely accessible via SOAP).
<p>
<div class="code"><pre>
using System;
using System.Web.Services;
public class MathService : WebService {
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}
}
</pre></div>
<p>
Web Service files are saved under the <b>.asmx</b> file extension. Like .aspx files, these are automatically compiled by the ASP+
runtime when a request to the service is made (subsequent requests are serviced by a cached pre-compiled type object).
In the case of our simple MathService, we have defined the WebService class in the .asmx file itself. Note that if an .asmx file is
simply requested by a browser, the ASP+ runtime returns a description of the SDL contract for that service as a web page.
The MyWebApplication.MyWebService defines the WebService class, and is contained in the /bin subdirectory of the ASP+ application.
<p>
<h5>Consuming a Web Service from a Client Application</h5>
To consume this service is very simple. You simply use the WebServiceUtil application that is included on the SDK to create a proxy class that looks similar to the class defined in the .asmx file. (Though only the [WebMethod] methods will be there!) You then simply compile your code with this proxy class included.
<p>
The WebServiceUtil application takes a variety of command-line options, but the most important is /c:proxy, which tells the tool to create a proxy class and /pa:<uri> option, which takes an URI that is the service, where it can consume an SDL file which describes the service.
<p>
Once the proxy class exists, you can create objects based on it. Each method call made with the object will then go out to the URI of the Web Service (usually as a SOAP request).