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

BeginningASP.NET 2.0 with C# PHẦN 7 pps

76 321 0

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 76
Dung lượng 2,17 MB

Nội dung

12 Web Services Web services have been “the next great thing” for a little too long now. They were originally intro- duced as part of the .NET Framework in its first incarnation (although they have been present in Java for a lot longer). Web services are a method of making information available in a standard- ized way that could be accessed by any developer’s application over the Web. Web services can form a library or shared repository of information that could be anything from the latest weather forecast, a map of your local amenities, a mathematical function calculator, to the tracks and album cover of the CD that you just inserted into your CD-ROM drive. You should be aware, though, that a web service on its own isn’t an application. Web services aren’t rendered as web pages, or as exe- cutable files ( .exe); they come completely shorn of a user interface. It’s up to you as a developer to use them and integrate them into your applications. They are there to save you time and effort by reducing code duplication. They can be used in one of two ways. You can create a web service that is exposed to the web, to share with other developers and other applications. Or you can search for a web service that can be added to your own application. (They are similar to plug-ins in that respect.) For example, if your application is a company web site and you want to include directions to company headquar- ters, rather than scan in a map, or attempt to hand-draw one in a graphics tool, why not use one of the web services that makes sections of maps available online? The information contained in the web service is wrapped up as an XML document (in other words, plain text), so that worries about platform-specific concerns, such as whether you’re access- ing them on an old Windows 98 machine or a turbo-powered Powerbook, simply evaporate. Web services aren’t really anything new either — components have been performing a similar trick for many years now. However, there are some crucial differences. Components had to be distributed by the developer, and they had to be downloaded and installed. These things alone meant that they tended to be tied to one platform. This isn’t true of web services. A key word that emphasizes what web services offer is standard. Everything to do with web services is standardized: the method of transmission, the method used to wrap the web service up, the way the web service is defined, all have clear W3C standards associated with the technologies involved. And to make life much easier, all these standards are based on XML. So they’re quick and easy to download, and even easier to use. 15_042583 ch12.qxd 4/4/06 2:49 PM Page 425 This chapter looks at the following: ❑ Introducing web services ❑ Consuming web services ❑ What happens in the typical life cycle of a web service ❑ Testing a web service ❑ Discovering a web service ❑ Creating and consuming an example web service that uses a parameter ❑ Creating a proxy — the old way of doing things ❑ Web service security Looking at Web Services The introduction alluded to the fact that web services haven’t quite taken off in the way that was expected, and it’s true and there are probably several reasons for that, but none that should stop you from using them. One is that developers and businesses don’t like giving away their hard work for free. The truth is when businesses create a web service, it usually isn’t for public consumption. It is for in- house use only, and even if it is available for the public to use, it is likely to come at a price. On the flip- side, with free web services, you have no guarantee that they will still be there in a week or a year’s time, so it’s no good basing a large application around them. So do you fork out for a web service and increase the cost of your application, or take a gamble that a particular service will still be in existence over the next few years? This dilemma isn’t easily remedied. Second is lack of education. People are still largely unaware of what web services can offer. I recently worked on a customer services application, which had to integrate with an existing contacts manager application and detect when the contacts manager was running and if it had loaded the latest customer information correctly. Rather than use a web service to make this information available, the client chose instead to write to the clipboard (especially awkward considering the users themselves might also be using the clipboard) and then my application had to periodically check the clipboard for the text to indi- cate that the contacts manager was running. As a result, the application was 20 times more complicated than it needed to be. Third is the lack of a single killer application. Before you started this chapter, could you name five com- mon examples of web services? The problem is that they’re too good at the job they do, so they become practically invisible. Where is the Google or Internet Explorer of web services? I don’t know, but you might just be using it unwittingly. A good web service should dovetail seamlessly into your application, and your user should never know it’s there. Last is the apparent learning curve required. With web services, it’s easy to get drawn into listing the mass of technologies involved, and therefore easy to get confused about what you need to know. SOAP, WSDL, UDDI, and DISCO all play valid parts in the process of making a web service available. However, you don’t need to know about any of these acronyms to be able to use a web service. In fact, before you start creating a web service and learning what goes into them, it’s a good idea to look at an example first. 426 Chapter 12 15_042583 ch12.qxd 4/4/06 2:49 PM Page 426 Consuming a Third-Party Web Service Consuming a web service is almost as easy as firing up your browser, typing in a URL of a web service, and pressing Return. Perhaps we’re oversimplifying a little bit here, but if you browse to the URL of a web service endpoint, you will find that you can use it functionally, albeit without any graphical frills. An endpoint is the specific location where the web service can be accessed. So let’s do exactly that. Because of the nature of the Web, sites are very often up and down. If you wanted to phone up a plumber on the other side of the city, you’d check your local phone directory for a number — but that plumber may or may not still be in business, and web services are just the same. Several good starting points are the following sites: www.webservicex.net, www.webservicelist.com, www.webservice oftheday.com , and www.wsiam.com. All of these sites provide lists of web services you can browse. More alternatives are available, and if one of these sites is inoperable, another will be working. There are plenty of possibilities to integrate web services into your example site. Wrox United chronicles the football fixtures, results, merchandise, and news of one soccer team. Now Wrox United isn’t always the most successful soccer team in the league, and they’re usually looking for an excuse on which to hang a particularly poor performance, such as the weather. It would be nice if you could stick a weather report on the bottom of your match reports, just so you know that if the goalkeeper claims the fifth and sixth goals slipped through his hands, maybe the 85-degree temperature would be a bit of a giveaway. In the following Try It Out, you start by finding an example weather web service that is freely available. Try It Out Consuming an Example Web Service 1. To be able to access a web service, you need to locate an .asmx file (you’ll learn what one of those is after you’ve finished this example). Figure 12-1 shows an example of a weather service at www.webservicex.net/globalweather.asmx. Figure 12-1 If for any reason this web service is giving an HTTP error 404, go back to any of the previous web service directories, type Weather into the search link, and use one of the example sites it returns. Most weather web services work the same way. 427 Web Services 15_042583 ch12.qxd 4/4/06 2:49 PM Page 427 2. There are two possible web services here. The format and style of this screen are the same for any .asmx web service file you browse. The link to the web service that gives you the weather forecast is called GetWeather. Click this link, and you’ll arrive at a screen similar to Figure 12-2. Figure 12-2 3. Supply the name of the city where you live, or closest to where you live, and the name of the country. Scroll down and look at the code (see Figure 12-3). Figure 12-3 428 Chapter 12 15_042583 ch12.qxd 4/4/06 2:49 PM Page 428 4. Click Invoke to get the result, shown in Figure 12-4. It will be customized to where you live and is dependent on the weather of the moment. Figure 12-4 How It Works You’ve just consumed a web service. The Wrox United application does not have the capability to do weather forecasting, so you looked elsewhere to get this service. By browsing to an .asmx file, you are able to use the web service, and supply input and get an answer tailored to your specifics. When you supplied the city name and country name, you probably noticed that your input was wrapped up in an XML document. This is the document broadcast to the server. Although the data can be wrapped up by three different methods, just look at the first on the page for now: POST /globalweather.asmx HTTP/1.1 Host: www.webservicex.net Content-Type: text/xml; charset=utf-16 Content-Length: length SOAPACTION: “http://www.webserviceX.NET/GetWeather” <?xml version=”1.0” encoding=”utf-16”?> <soap:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”> <soap:Body> <GetWeather xmlns=”http://www.webserviceX.NET”> <CityName>string</CityName> <CountryName>string</CountryName> </GetWeather> </soap:Body> </soap:Envelope> Your input is simply substituted for the words string in the highlighted code: <GetWeather xmlns=”http://www.webserviceX.NET”> <CityName>Birmingham</CityName> <CountryName>United Kingdom</CountryName> </GetWeather> 429 Web Services 15_042583 ch12.qxd 4/4/06 2:49 PM Page 429 Of course one big drawback is that there isn’t a user interface, so you’re using a normal interface, and also all your code is returned as one large lump of XML. So it’s not exactly something you’d stick into your application as it is, without your users getting confused. Also you’ll see that the weather report is much too detailed for your match reports. Ideally you’d just want to be able to pick out, say, sky condi- tions and temperature and probably leave it at that. To be honest, a few other pitfalls exist that would make a weather service difficult to integrate into your application. Not least is the fact that the weather service extracts the current weather, and if you were to display this in your match reports, you’d need to make sure you saved the weather in the database alongside the match details, otherwise you’d be read- ing about Wednesday’s match, and seeing Friday’s weather. Later in the chapter, you’ll look at creating some web services for the Wrox United application, but for now you only need to understand that web services are freely available for very ordinary chores to all sorts of weird and wonderful things. If there is a URL with an .asmx file available, you can access and use the web service in a standard way. And if you can access and use the web service in this standard way, you can stick it in your application just as easily. The Life Cycle of a Web Service It’s time to look at some theory behind what is happening here. This section strips down a web service to its basic essentials, which is a four-stage process. Following that, this section expands upon each stage, and talks a little bit about the technologies and standards used at each step. The four-stage process of a web service is as follows (as detailed in Figure 12-5): 1. The client calls web service over a protocol. 2. The client sends the method to the server, which contains instructions on what is needed from the web service. 3. The server returns values and/or an acknowledgment that it has received the method. 4. The client gets the results and acts on the received information. This may involve calling the web service again, or a different web service, with the results received. Figure 12-5 Client calls web service Server returns values or an acknowledgement Client sends method Client acts on information 430 Chapter 12 15_042583 ch12.qxd 4/4/06 2:49 PM Page 430 This can happen as a cyclical process, where information is sent and received, acted upon, and sent out again. In the next several sections, each step of the process is put under the magnifying class because with web services, there are usually quite a few interesting things going on. Calling the Web Service When you ran the first example and consumed the simple web service, you did so by typing a URL into a browser. However when you type the URL, you also specify the protocol that you are using (for exam- ple, http://). This is important, because web services are able to work over a multitude of protocols from SMTP (Simple Mail Transport Protocol) to HTTP (secure HTTP). However, using anything other than HTTP is beyond the scope of this book, and you can achieve plenty just using the HTTP protocol, but you shouldn’t think that you are restricted in this way. ASP.NET passes information backward and forward using the HTTP-Request/Response system. Any information is sent to the web service as part of the request, and the server will return anything from the web service as part of the response. Most commonly, you can transmit values to a web service via an HTML form and the standard HTML controls. The request that is sent to the web service contains the following information: ❑ The web service’s URL ❑ The fact that it is an HTTP request ❑ The amount of information being sent ❑ The type of document you want back from the web service ❑ Information about the client ❑ The date of the request ❑ The parameters you want to send to the web service The browser collects the information from the form and wraps it up in a document ready for transmis- sion. This process is called serialization. Transmitting the Web Service When you transmit the information required by the web service, as you’ve seen already, it is serialized in an XML document. This can be done in three different ways: ❑ HTTP-GET via the querystring ❑ HTTP-POST via the body of the form ❑ SOAP via the body of the form You already know about the first two methods, so this section focuses on the last one. The phrase “serial- ized in an XML document” doesn’t tell the whole story with SOAP. SOAP isn’t just any type of XML, but a specific dialect specially created for the exchange of messages. SOAP used to stand for Simple Object Access Protocol, but these days it is commonly regarded as not standing for anything in particular. A message contained in SOAP is nothing more than a well-formed XML document or plain, vanilla text. So what exactly is SOAP’s purpose? 431 Web Services 15_042583 ch12.qxd 4/4/06 2:49 PM Page 431 SOAP is a message template for sending requests and receiving responses to web services between the browser and the web service. Because the web relies on the HTTP protocol, it commonly excludes any- thing other than HTTP; so SOAP (XML) documents have to be sent as part of the HTTP data. SOAP will send a particular instruction such as “Get me a certain bit of information” wrapped in the HTTP, and then this information can be retrieved by the web service at the other end. In the previous Try It Out, underneath the text boxes into which you entered the name of a city and country, you saw some example code. The example code took the three formats: HTTP-GET, HTTP-POST, and SOAP. The SOAP document looked like this: POST /globalweather.asmx HTTP/1.1 Host: www.webservicex.net Content-Type: text/xml; charset=utf-16 Content-Length: length SOAPACTION: “http://www.webserviceX.NET/GetWeather” <?xml version=”1.0” encoding=”utf-16”?> <soap:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”> <soap:Body> <GetWeather xmlns=”http://www.webserviceX.NET”> <CityName>string</CityName> <CountryName>string</CountryName> </GetWeather> </soap:Body> </soap:Envelope> The first thing to note is that the document was split into two sections. The first section is a set of HTTP headers that are used to communicate various aspects about your document. HTTP headers are also sent as a matter of course with HTML page requests so there’s nothing new here. Take a brief look at the HTTP headers to see what they indicate. The first line indicates that you are sending information via the HTTP-POST method. This might seem to immediately contradict the fact that you are using SOAP, but your SOAP message has to be sent as or in an HTTP request to allow it to get through to most web servers. It also specifies the endpoint of your ser- vice, globalweather.asmx. The next three lines of HTTP headers are pretty standard, but the final header, the SOAPACTION header, must be present; otherwise the message will be invalid. It’s there to help the server decide whether it can let through a message’s content. The XML document is of greater interest. The opening line is the XML document header, standard to all XML documents. Then you have the structure of the document, which in SOAP will always have this structure. You have a SOAP Envelope tag that contains a SOAP Header and a SOAP Body. The SOAP Header is optional and is missing from the code, but the SOAP Envelope contains some vital information in the attributes to help it make up the document. It contains three attributes that all provide namespace information: xsi, xsd, and soap. xmlns is short for XML namespace. At this level of pro- gramming, you really only want to know about the latter attribute, and this is because you use it to spec- ify a prefix to your SOAP tags: xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/” The prefix specified after the xmlns: attribute is soap, and this prefix is used in front of all the SOAP tags: 432 Chapter 12 15_042583 ch12.qxd 4/4/06 2:49 PM Page 432 <soap:Envelope> <soap:Body> Web Service content here <soap:Body> <soap:Envelope> All documents sent by SOAP will need to adhere to this structure. Inside the SOAP:Envelope attribute is the SOAP:Body tag. The SOAP:Body tag is always contained within the envelope and it contains the information that has been gleaned from the parameters and needs to be sent to the web service. Inside the SOAP:Body tags, you find at last the data you want to send: <GetWeather xmlns=”http://www.webserviceX.NET”> <CityName>Birmingham</CityName> <CountryName>United Kingdom</CountryName> </GetWeather> The GetWeather tag is the web service, and the xmlns attribute outlines the location of the web service, which in this case is www.webservicex.net. Inside the GetWeather tag are two tags: CityName and CountryName. These are the two parameters that you originally supplied to the web service when you invoked it. These parameters have been serialized into a SOAP document, which itself is parceled up in the HTTP data and is now transmitted to the web service. You’re probably wondering why we’re going into some quite esoteric detail about SOAP document structure. The answer is that if you want to supply data to the web service manually, it is going to have to have this structure involved. Also there is another important reason, which you will discover in the next sections. Returning the Response A web service doesn’t have to return a response. It will most commonly return a response, but this isn’t essential — it might be just enough to send some information to a database or to change an attribute on the server. Before a response of any sort can be returned, though, a few tasks must be accomplished by the web service. Because the data has been serialized so that it can be transmitted across the web, it has to be deserialized first. This is just the process of obtaining the data (which in the previous example were the words “Birmingham” and “United Kingdom”) from the XML and then executing the web service with this data. Of course the data isn’t the only thing sent back as part of the response. You also get the following: ❑ A return address for the consumer ❑ The fact that this is an HTTP response and that there is no further action required ❑ A success or failure code ❑ Configuration information Rather than use the more common terminology call, the term invoke is used with relation to web services. If you check Dictionary.com, you will find the definition of invoke is to call upon a “higher system or power for assistance, support or inspira- tion.” The higher power in this instance is of course the web service. I suppose it is used because the word call, of course, just doesn’t paint the same picture. 433 Web Services 15_042583 ch12.qxd 4/4/06 2:49 PM Page 433 One of two scenarios is possible: either a value needs to be returned, in which case the result has to be serialized once more in an XML document and sent back to the client, or there are no values that need transmitting back, in which case there will only be a success or failure code to indicate what has hap- pened to your web service. In the example, you might notice that the response isn’t actually returned as a SOAP document, but one large XML string using the HTTP-POST protocol. This is because you sent your original call to the service as a HTTP-POST document, so the web service is just returning in like format. It is also possible to call your web service using HTTP-GET. As you might remember from Chapter 2, a call to the server using HTTP-GET involves adding a querystring to the URL and adding the parameters as querystrings. You can send the same request to the example web service as follows: http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=Birmingham&Coun tryName=United%20Kingdom Doing this will return exactly the same response as you saw in Figure 12-4. This leaves the SOAP message template. To send and retrieve a document using SOAP requires a little more effort, and isn’t possible via the endpoint without extra code. However, the information contained with a SOAP document retains structure, rather than being sent back as a convoluted jumble bundled in a <string> element: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-16 Content-Length: length <?xml version=”1.0” encoding=”utf-16”?> <soap:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”> <soap:Body> <GetWeatherResponse xmlns=”http://www.webserviceX.NET”> <GetWeatherResult> <Location>Birmingham / Airport, United Kingdom (EGBB) 52-27N 001-44W 0M</Location> <Time>Jul 12, 2005 - 05:20 AM EDT / 2005.07.12 0920 UTC</Time> <Wind> from the E (090 degrees) at 5 MPH (4 KT) (direction variable):0</Wind> <Visibility> greater than 7 mile(s):0</Visibility> <SkyConditions> mostly cloudy</SkyConditions> <Temperature> 64 F (18 C)</Temperature> <DewPoint> 59 F (15 C)</DewPoint> <RelativeHumidity> 82%</RelativeHumidity> <Pressure> 30.47 in. Hg (1032 hPa)</Pressure> <Status>Success</Status> </GetWeatherResult> </GetWeatherResponse> </soap:Body> </soap:Envelope> The first three lines are the HTTP header. However, this time the weather report results (which are dif- ferent than what was shown in Figure 12-4 because it was done on a different day) are placed within the 434 Chapter 12 15_042583 ch12.qxd 4/4/06 2:49 PM Page 434 [...]... 1 With the Chapter12 solution (C:\BegASPNET2\Chapters\Begin\Chapter12) open, go to Solution Explorer and select the top line, which reads C:\ \Chapter12 Right-click it and select Add New Item 2 438 A new dialog box appears Make sure that the Language is set to Visual C# Type the name FixtureService.asmx, select the Web Service option, and click Add, as shown in Figure 12 -7 Web Services Figure 12 -7. .. web service: public class Service : System.Web.Services.WebService { } The class name needs to correspond with the class attribute that is specified within the processing directive Then for all other intents and purposes, it is just a normal object, albeit one that is exposed to the web The trick with this web server, though, is that any calls to the object will look like they came from the same machine,... wasn’t always as easy as it should have been If you created ASP.NET 1.x pages with Notepad, you would find yourself delving around the murky world of the command prompt to compile the service, and having to create an application by hand with which to consume the service Here you’re only going to worry about creating a web service with which you can call and transmit the data In this Try It Out, you create... particulars of your web service The class should be a separate file Namespaces As with the rest of ASP.NET, occasionally you will need to specify other namespaces so that you can appropriate other classes and functions within your own web service These namespaces are defined after the @WebService attribute in the file In C#, four references are added as default, which are as follows: using using using... were created at the same time This means can access the web service from within your code This is the ultimate point of your web service and you’re almost there now Adding the Fixture Ser vice to Your Application The web service now exists as an object within your code that you can access and query the methods of, just like you would with any normal object In fact, to your application, for all intents... only three teams, and will return the teams in fourth, fifth, and sixth Your second condition deals with what happens if Wrox United is top You check to see if the position is 1, you set the offset to 0, (1-1), and then you fill the adapter at the end of the if condition with the dataset starting at row 0, with the next three teams: else if (position == 1) { offset = position - 1; } Last, you can deduce... sending via SSL, then anyone is able to intercept and steal the code A couple of new facilities in ASP.NET 2.0 help you deal with this Encryption and Message-Based Security Encryption is the process of scrambling the text containing your web service so that only the intended reader is able to decrypt it with the aid of a key Message-based security was introduced in web services Message-based security allows... information contained within the string as best we can In the real world, we suggest that you use SOAP For more details, look at http://msdn.microsoft.com/webservices/ The Structure of Your Web Ser vice A web service has a particular structure that needs to be maintained whenever you create a new web service This structure is pretty much unchanged between ASP.NET 1.x and ASP.NET 2.0, so if you have experience... the web, but in ASP.NET 2.0, you can also expose properties The [WebMethod] declaration is the part that does all of the legwork You can define one or more web methods, and not only that, you can make sure some web methods are publicly accessible, whereas others can have access to them restricted via the protected keyword Though the syntax varies slightly between VB.NET and C# (VB.NET uses greater-than... and expand each node within Internet Explorer After the element are various , , and elements, which all refer to transmissions between the web service and consumer The WebMethod message named FixtureService is contained in here, and various SOAP message structures are defined In short, this file has everything needed to handle communication with your web service . 52- 27N 00 1-44W 0M</Location> <Time>Jul 12, 20 05 - 05 : 20 AM EDT / 20 05 . 07 . 12 0 9 20 UTC</Time> <Wind> from the E (09 0 degrees) at 5 MPH (4 KT) (direction variable) :0& lt;/Wind>. XML depicted in Figure 12- 11. 441 Web Services 15 _0 425 83 ch 12. qxd 4/4 /06 2: 49 PM Page 441 Figure 12- 10 Figure 12- 11 4 42 Chapter 12 15 _0 425 83 ch 12. qxd 4/4 /06 2: 49 PM Page 4 42 How It Works You can. example sites it returns. Most weather web services work the same way. 4 27 Web Services 15 _0 425 83 ch 12. qxd 4/4 /06 2: 49 PM Page 4 27 2. There are two possible web services here. The format and style

Ngày đăng: 09/08/2014, 14:20

TỪ KHÓA LIÊN QUAN