14.3. Creating a Web Service That Returns a Custom Object


You want to create a web service that returns a custom object because none of the .NET data types meets your needs.


Create a class that encapsulates the data you need and use it as the return type of a method of your web service.

To demonstrate this solution, we have created the custom class, BookData, shown in Examples 14-11 (VB) and 14-12 (C#). The class encapsulates information about books stored in a database. A class that uses a web service that returns book information from a database using the custom class is shown in Examples 14-13 (VB) and 14-14 (C#). Examples 14-15, 14-16 through 14-17 show the .aspx file and VB and C# code-behind files for our application that demonstrates how we use the web service. Figure 14-4 shows the Solution Explorer in Visual Studio 2005 with the files used for this recipe and other recipes in this chapter.

Solution Explorer showing files for this recipe

Figure 14-4. Solution Explorer showing files for this recipe


Web services use XML to transfer data, and rely on the CLR to serialize most data types to XML. If you create an object that contains public properties or variables of the types the CLR can serialize, the CLR will serialize the object for you with no additional coding when it is used as the return type of a web service.

A custom object to be returned by a web service must meet two requirements. First, the object ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.