Creating a Web Service

At its simplest, creating a web service in .NET can be almost trivially easy. I’m going to start with a simple inventory query service. Example 10-2 shows the basic ASP.NET skeleton for such a service.

Example 10-2. InventoryQuery.asmx source code
<%@ WebService Language="C#" Class="InventoryQuery" %>

using System.Web.Services;

[WebService(Namespace="http://angushardware.com/InventoryQuery")]
public class InventoryQuery : WebService {
  [WebMethod]
  public int GetNumberInStock(string productCode) {
    return 0;
  }
}

Let’s break this skeleton down into its basic components.

The presence of the @ WebService directive in a file with the .asmx extension tells the ASP.NET provider that the web service is located at InventoryQuery.asmx, that the web service’s source code is written in C#, and that the implementation is in the class named InventoryQuery. The code could also be written in JScript .NET (JS) or Visual Basic .NET (VB). Additionally, the code could actually reside in a separate file, compiled into an assembly located in the .\Bin directory relative to the .asmx file:

<%@ WebService Language="C#" Class="InventoryQuery" %>

Warning

There is no restriction on the name of the assembly containing the class that implements a web service, and multiple web services may exist in the same directory. However, if multiple assemblies in the .\Bin directory each contain a class with the name listed in an .asmx file, there is no guarantee which one will be used when that ...

Get .NET & XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.