Return An Object From A Web Service

Returning objects from a Web Service enables you to pass very complex return information to the Web Service Client. You can define your own objects and return objects from a Web Service. For example, you can define a Goal class and return a Goal object from your Web Service.

You can return an object from a Web Service if the Web Service has access to a class declaration. The class declaration defines which members are parts of the class. For example, adding a Goalid property to the class and specifying the data type for the property allows for storage of a Goal Identifier. This would be repeated for other required members of the class. With this class, you can use the name of the class as the return type for the Web Method.

In a Web Method that returns a class, you create a new object as the object type defined in the Web Service file and then populate the properties of the object. This stateful object can then be passed back to the client. The client uses the returned object to obtain values it needs by accessing the object's properties. For more information on working with objects and object properties, see page 44.

RETURN AN OBJECT FROM A WEB SERVICE

4S Untitled Notepad

^JiiJI

| File Edit Format Help |

1 <%@ WebSeivice Language="C#" Class=|"ObjectWebSeivice"|%>

A

using System;

using System. Web.Servi ces;

d

D Open the WebServices Template.aspx template from the Code Templates directory.

0 Rename the class to ObjectWebService.

D Open the WebServices Template.aspx template from the Code Templates directory.

0 Rename the class to ObjectWebService.

^0 Create a public class for goals.

□ Create GoalId, Type, and Name properties for a goal.

^0 Create a public class for goals.

□ Create GoalId, Type, and Name properties for a goal.

WORK WITH WEB SERVICES

You can determine which instance of an object to return based on an input parameter of the Web Services Method.

TYPE THIS:

<%@ WebService Language="C#" Class="ObjectWebService_ai" %> using System; using System.Web.Services;

public class Goal{

public int GoalId; public string Type; public string Name;

public class ObjectWebService_ai : WebService {

[WebMethod] public Goal GetTravelGoal(int intGoalId) { Goal goalUser = new Goal(); switch(intGoalId){ case 1:

goalUser.GoalId = 1; goalUser.Type = "Travel"; goalUser .Name = "Travel to all seven continents" break; case 2:

goalUser.GoalId = 2; goalUser.Type = "Travel"; goalUser.Name = "Travel to Asia"; break; default:

goto case 2;

return goalUser;

RESULT:

A Web Service that will return an object that has a state that depends on what is passed into the Web Service Method. The return is a stateful Goal object.

Local intranet

H Add a WebMethod that returns the Goal class.

Q Set the GoalId, Type, and Name properties.

^0 Return the object.

• Save the file and test the Web Service.

■ The Goal object returns from the Web Service.

Was this article helpful?

0 0

Post a comment