O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.3. Creating a Web Service That Returns a Custom Object

Problem

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

Solution

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 Example 11-11 (VB) and Example 11-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 Example 11-13 (VB) and Example 11-14 (C#). Example 11-15 through Example 11-17 show the .aspx file and VB and C# code-behind files for our application that demonstrates how we use the web service.

Discussion

Web services use XML to transfer data, and rely on the common language runtime (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 that is to be returned by a web service must meet two requirements. First, the object must contain only data types that can be serialized (they must implement the ISerializable interface). All of the .NET base data types and the majority of its complex data types can be serialized. The notable exceptions are DataTable

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required