1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 3.5 in C# and Visual Basic Part 138 docx

10 268 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Building and Consuming Services
Tác giả Evjen
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Thesis
Năm xuất bản 2008
Thành phố City Name
Định dạng
Số trang 10
Dung lượng 572,06 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

This visual inter-face to your Web service is really meant either for testing purposes or as a reference page for developers interested in consuming the Web services you expose.. The pag

Trang 1

❑ Description: Applies a text description to theWebMethodthat appears on the.aspxtest page of the XML Web service

❑ EnableSession: SettingEnableSessiontoTrueenables session state for a particularWebMethod The default setting isFalse

❑ MessageName: Applies a unique name to theWebMethod This is a required step if you are work-ing with overloadedWebMethods (discussed later in the chapter)

❑ TransactionOption: Specifies the transactional support for theWebMethod The default setting

isDisabled If theWebMethodis the root object that initiated the transaction, the Web service can participate in a transaction with anotherWebMethodthat requires a transaction Other possible

values includeNotSupported,Supported,Required, andRequiresNew

The XML Web Service Interface

The Customers Web service from Listing 29-5 has only a singleWebMethodthat returns a DataSet contain-ing the complete Customers table from the SQL Server Northwind database

RunningCustomers.asmxin the browser pulls up the ASP.NET Web service test page This visual inter-face to your Web service is really meant either for testing purposes or as a reference page for developers interested in consuming the Web services you expose The page generated for the Customers Web service

is shown in Figure 29-3

Figure 29-3

The interface shows the name of the Web service in the blue bar (the dark bar in this black and white

image) at the top of the page By default, the name of the class is used unless you changed the value

through theDescriptionproperty of theWebServiceattribute, as defined earlier A bulleted list of

links to the entire Web service’sWebMethods is displayed In this example, there is only oneWebMethod:

GetCustomers

1333

Trang 2

A link to the Web service’s Web Services Description Language (WSDL) document is also available (the

link is titled Service Description in the figure) The WSDL file is the actual interface with the Customers

Web service The XML document (shown in Figure 29-4) is not really meant for human consumption; it is

designed to work with tools such as Visual Studio, informing the tool what the Web service requires to be

consumed Each Web service requires a request that must have parameters of a specific type When the

request is made, the Web service response comes back with a specific set of data defined using specific

data types Everything you need for the request and a listing of exactly what you are getting back in a

response (if you are the consumer) is described in the WSDL document

Figure 29-4

Clicking theGetCustomerslink gives you a new page, shown in Figure 29-5, that not only describes the

WebMethodin more detail, but it also allows you to test theWebMethoddirectly in the browser

At the top of the page is the name of the XML Web service (Customers); below that is the name of this

particularWebMethod(GetCustomers) The page shows you the structure of the SOAP messages that are

required to consume theWebMethod, as well as the structure the SOAP message takes for the response

1334

Trang 3

Below the SOAP examples is an example of consuming the XML Web service using HTTP Post (with

name/value pairs) It is possible to use this method of consumption instead of using SOAP (This is

discussed later in the ‘‘Transport Protocols for Web Services’’ section of this chapter.)

Figure 29-5

You can test theWebMethoddirectly from the page In the Test section, you find a form If the

WebMethodyou are calling requires an input of some parameters to get a response, you see some text

boxes included so you can provide the parameters before clicking the Invoke button If theWebMethod

you are calling does not require any parameters, you see only the Invoke button and nothing more

Clicking Invoke is actually sending a SOAP request to the Web service, causing a new browser instance with the result to appear, as illustrated in Figure 29-6

Now that everything is in place to expose the XML Web service, you can consume it in an ASP.NET

application

1335

Trang 4

Figure 29-6

Consuming a Simple XML Web Ser vice

So far, you have seen only half of the XML Web service story Exposing data and logic as SOAP to

dis-parate systems across the enterprise or across the world is a simple task using NET and particularly

ASP.NET The other half of the story is the actual consumption of an XML Web service into an ASP.NET

application

You are not limited to consuming XML Web services only into ASP.NET applications; but because this

is an ASP.NET book, it focuses on that aspect of the consumption process Consuming XML Web

ser-vices into other types of applications is not that difficult and, in fact, is rather similar to how you would

consume them usingASP.NET.Remember that the Web services you come across can be consumed in

Windows Forms, mobile applications, databases, and more You can even consume XML Web services

with other Web services so you can have a single Web service made up of what is basically an aggregate

of other Web services

Adding a Web Reference

To consume the Customers Web service that you created earlier in this chapter, create a new ASP.NET

Web site calledCustomerConsumer The first step in consuming an XML Web service in an ASP.NET

application is to make a reference to the remote object — the Web service This is done by right-clicking

1336

Trang 5

on the root node of your project from within the Solution Explorer of Visual Studio and selecting Add

Web Reference This pulls up the Add Web Reference dialog box, shown in Figure 29-7

Figure 29-7

The Add Web Reference dialog box enables you to point to a particular.asmxfile to make a reference to

it Understand that the Add Web Reference dialog box is really looking for WSDL files Microsoft’s XML Web services automatically generate WSDL files based on the.asmxfiles themselves To pull up the

WSDL file in the browser, simply type in the URL of your Web service’s.asmxfile and add a?WSDLat

the end of the string For example, you might have the following construction (this is not an actual web service, but simply an example):

http://www.wrox.com/MyWebService/Customers.asmx?WSDL

Because the Add Web Reference dialog box automatically finds where the WSDL file is for any Microsoft-based XML Web service, you should simply type in the URL of the actual WSDL file for any non–

Microsoft-based XML Web service

If you are using Microsoft’s Visual Studio and its built-in Web server instead of IIS, you will be required

to also interject the port number the Web server is using into the URL In this case, your URL would be

structured similar tohttp://localhost:5444/MyWebService/Customers.asmx?WSDL.

In the Add Web Reference dialog box, change the reference from the default name to something a little more meaningful If you are working on a single machine, the Web reference might have the name of

localhost; if you are actually working with a remote Web service, the name is the inverse of the URL,

1337

Trang 6

such ascom.wrox.www In either case, it is best to rename it so that the name makes a little more sense and

is easy to use within your application In the example here, the Web reference is renamedWroxCustomers

Clicking the Add Reference button causes Visual Studio to make an actual reference to the Web service

from theweb.configfile of your application (shown in Figure 29-8) You may find some additional files

under theApp_WebReferencesfolder — such as a copy of the Web service’s WSDL file

Figure 29-8

Your consuming application’sweb.configfile contains the reference to the Web service in its

<appSettings>section The addition is shown in Listing 29-6

Listing 29-6: Changes to the web.config file after making a reference to the Web

service

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

<appSettings>

<add key="WroxCustomers.Customers"

value="http://www.wrox.com/MyWebService/Customers.asmx"/>

</appSettings>

</configuration>

You can see that theWroxCustomersreference has been made along with the name of the Web service,

providing a key value ofWroxCustomers.Customers Thevalueattribute takes a value of the location of

the Customers Web service, which is found within theCustomers.asmxpage

Invoking the Web Service from the Client Application

Now that a reference has been made to the XML Web service, you can use it in your ASP.NET application

Create a new Web Form in your project With this page, you can consume the Customers table from the

remote Northwind database directly into your application The data is placed in a GridView control

On the design part of the page, place a Button and a GridView control so that your page looks something

like the one shown in Figure 29-9

1338

Trang 7

Figure 29-9

The idea is that, when the end user clicks the button contained on the form, the application sends a SOAP request to the Customers Web service and gets back a SOAP response containing the Customers table,

which is then bound to the GridView control on the page Listing 29-7 shows the code for this simple

application

Listing 29-7: Consuming the Customers Web service in an ASP.NET page

VB

<%@ Page Language="VB" %>

<script runat="server">

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

Dim ws As New WroxCustomers.Customers()

GridView1.DataSource = ws.GetCustomers()

GridView1.DataBind()

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Web Service Consumer Example</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button ID="Button1" Runat="server" Text="Get Customers"

OnClick="Button1_Click" />

<br />

<br />

<asp:GridView ID="GridView1" Runat="server" BorderWidth="1px"

BackColor="#DEBA84" CellPadding="3" CellSpacing="2" BorderStyle="None"

BorderColor="#DEBA84">

<FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle>

<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center"></PagerStyle>

<HeaderStyle ForeColor="White" Font-Bold="True"

BackColor="#A55129"></HeaderStyle>

<SelectedRowStyle ForeColor="White" Font-Bold="True"

BackColor="#738A9C"></SelectedRowStyle>

Continued

1339

Trang 8

<RowStyle ForeColor="#8C4510" BackColor="#FFF7E7"></RowStyle>

</asp:GridView>

</div>

</form>

</body>

</html>

C#

<%@ Page Language="C#" %>

<script runat="server">

protected void Button1_Click(Object sender, EventArgs e) {

WroxCustomers.Customers ws = new WroxCustomers.Customers();

GridView1.DataSource = ws.GetCustomers();

GridView1.DataBind();

}

</script>

The end user is presented with a simple button Clicking it causes the ASP.NET application to send a

SOAP request to the remote XML Web service The returned DataSet is bound to the GridView control,

and the page is redrawn, as shown in Figure 29-10

Figure 29-10

1340

Trang 9

The Customers Web service is invoked by the instantiation of theWroxCustomers.Customersproxy

object:

Dim ws As New WroxCustomers.Customers()

Then you can use thewsobject like any other object within your project In the code example from

Listing 29-7, the results of thews.GetCustomers()method call is assigned to theDataSourceproperty of the GridView control:

GridView1.DataSource = ws.GetCustomers()

As you develop or consume more Web services within your applications, you will see more of their

power and utility

Transpor t Protocols for Web Ser vices

XML Web services use standard wire formats such as HTTP for transmitting SOAP messages back and forth, and this is one of the reasons for the tremendous popularity of Web services Using HTTP makes using Web services one of the more accessible and consumable messaging protocols when working

between disparate systems

The transport capabilities of Web services are a fresh new addition to the evolutionary idea of a

mes-saging format to use between platforms DCOM, an older mesmes-saging technology that was developed to address the same issues, uses a binary protocol that consists of a method-request layer riding on top of

a proprietary communication protocol One of the problems with using DCOM and similar methods for calling remote objects is that the server’s firewall usually gets in the way because DCOM flows through some odd port numbers

Web services, on the other hand, commonly use a port that is typically open on almost every server — port

80 The port is used for HTTP or Internet traffic Moving messages from one system to another through port 80 over HTTP is sensible and makes consumption of Web services easy

An interesting note about XML Web services is that, although many people still think of Web services as SOAP going over HTTP, you can actually consume the Web service in a couple of different ways Three wire formats are available to Web services: HTTP-GET, HTTP-POST, and SOAP

Listing 29-8 shows how to work with these different wire formats by consuming a simple Addition Web service

Listing 29-8: The Addition Web service

VB

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

<WebService(Namespace := "http://www.wrox.com/addition/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

Public Class WroxMath

Continued

1341

Trang 10

Inherits System.Web.Services.WebService

<WebMethod()> _

Public Function Addition(ByVal a As Integer, ByVal b As Integer) As Integer

Return (a + b) End Function

End Class

C#

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

[WebService(Namespace = "http://www.wrox.com/addition/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class WroxMath : System.Web.Services.WebService

{

[WebMethod]

public int Addition(int a, int b) {

return a + b;

}

}

The Addition Web service takes two parameters:aandb The Web service then adds these numbers

and returns the result in a SOAP message You might typically consume this Web service by sending a

request SOAP message to the service Now look at some of the other means of consumption

HTTP-GET

The use of HTTP-GET has been rather popular for quite awhile It enables you to send your entire request,

along with any required parameters, all contained within the URL submission Here is an example of a

URL request that is passing a parameter to the server that will respond:

http://www.reuters.com?newscategory=world

In this example, a request from theReuters.comWeb site is made, but in addition to a typical Web

request, it is also passing along a parameter Any parameters that are sent along using HTTP-GET

can only be in a name/value pair construction — also known as querystrings This means that you can

have only a single value assigned to a single parameter You cannot provide hierarchal structures through

querystrings As you can tell from the previous URL construction, the name/value pair is attached to the

URL by ending the URL string with a question mark, followed by the variable name

Using querystrings, you can also pass more than a single name/value pair with the URL request as the

following example shows:

http://www.reuters.com?newscategory=world&language=en

In this example, the URL construction includes two name/value pairs The name/value pairs are

sepa-rated with an ampersand (&)

1342

Ngày đăng: 05/07/2014, 19:20

TỪ KHÓA LIÊN QUAN