首页 > 开发 > 综合 > 正文

Web Services: Building Reusable Web Components wit

2024-07-21 02:21:36
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • web services: building reusable web components with soap and asp.net
    david s. platt

    this article assumes you’re familiar with xml and visual basic
    level of difficulty 1 2 3
    download the code for this article: webcomp.exe(93kb)
    browse the code for this article at code center: timeservicedemo
    summary xml and http are cross-platform technologies especially suited for building applications that can communicate with each other over the internet, regardless of the platform they are running on. web services in the microsoft .net framework make it easy to write components that communicate using http get, http post, and soap.
    an understanding of these concepts, along with knowledge of synchronous and asynchronous operations, security, state management, and the management of proxies by the .net framework is essential in building these applications.
    this article has been adapted from david platt’s upcoming book introducing the microsoft .net platform to be published by microsoft press in spring 2000.
    --------------------------------------------------------------------------------

    seismic shift is just now beginning in internet programming. internet access will soon be built into nearly every program anyone ever writes. you won't use a generic browser, except when you feel like browsing generically. instead, you will use dedicated programs that are optimized for accomplishing specific tasks. you won't be aware of the program's internet access (except when it breaks).
    an early example of this type of program is napster, which allows you to search the shared hard drives of thousands of participating users for music files that meet specified criteria, and download the ones you like. the dedicated user interface of a multi-player game is another example of hidden internet access. and the latest edition of microsoft® money does a good job of seamlessly blending web content (current stock quotes, latest balances, and so on) and desktop content (financial plans you create locally).
    in order to develop programs of this type, there needs to be a quick and easy way (which, in turn, means a cheap way) to write code that communicates with other programs over the internet. the idea isn't new; there are a number of existing technologies that enable this type of communication: rpc, dcom, and microsoft message queue services (msmq). each of these techniques is cool in itself, but they all share one fatal failing: they only work from one similar system to another. msmq talks only to msmq, a dcom client only to a dcom server, and so on.
    what's really needed is universal programmatic access to the internet—some way for a program on one box to talk to any other program on any other box. it has to be independent not only of the operating system, but also of the programs' internal implementations. (is it c++ or visual basic®? which vendor is it from? which version is it? right now you can barely solve this problem on a single desktop.) and it has to be easy to program, or no one will be able to afford it.

    solution architecture
    the only way to deal with the enormous numbers of heterogeneous entities on the internet is to use the lowest common denominator. in other words, when bytes are transferred from one box to another, the process needs to use some standard that everyone on the internet supports. the most common internet transfer protocol is http, which is used today by essentially all web browsers to request the pages they display. the emerging cross-platform standard for encoding pure information transferred over http is xml.
    microsoft put these ideas together and developed the concept of a web service—a seamless way for objects on a server to accept incoming requests from clients using http and xml. to create a web service, you simply write a microsoft .net server object as if it were going to be accessed directly by local clients, mark it with an attribute that says that you want it to be available to web clients, and let asp.net do the rest. it automatically hooks up a prefabricated infrastructure that accepts incoming requests through http and maps them to calls on your object, as shown in figure 1. by rolling them into a web service, your objects can work with anyone on the web who speaks http and xml, which should be everybody. you do not have to write the infrastructure that deals with web communication—the operating system provides it for you.


    figure 1 handling http requests

    on the client side, .net provides proxy classes that have easy, function-based access to the web services provided by any server that accepts http requests, as shown in figure 2. a developer tool reads the description of the web service and generates a proxy class containing functions in whatever language you're using to develop the client. when your client calls one of these functions, the proxy class generates an http request and sends it to the server. when the response comes back from the server, the proxy class parses the results and returns them from the function. this allows your function-based client to seamlessly interact with any web server that speaks http and xml.


    figure 2 proxy classes

    writing a web service
    as i always do when explaining a new piece of technology, i wrote the simplest program i could to demonstrate web services. this sample web service provides the current time of day on its machine in the form of a string, either with or without the seconds digits. you can download the sample code for this service from the link at the top of this article to follow this description more closely. you will need to download and install the microsoft .net sdk if you want to run it as well.
    i wrote this web service in the form of an .asmx page to avoid distracting you with other software packages. i first installed the .net sdk. then i used the administrative tools in microsoft internet information services (iis) to set up a virtual directory pointing to the folder in which i would do my service file development. then i wrote my asp.net code in a file called timeservice.asmx on my server.
    writing the web service was incredibly easy; i did it in notepad (see figure 3). while it's quite simple, there are a few constructs that are probably new to you, so let's go over it section by section. (you should note that the code in this article is based on pre-beta 1 bits and the calls may change somewhat before the final release.) the program starts with the standard asp.net salutation <%@...%>. in it, the webservice directive tells asp.net that the code on the page is to be exposed as a web service. the language attribute tells asp which language to compile the page's code in accordance with. i've chosen visual basic because it's familiar to the majority of developers. asp.net will use visual basic.net to compile the code. you do not have to install visual studio&reg;; all the language compilers come with the .net sdk. the class attribute tells asp.net the name of the class of object to activate for incoming requests addressed to this service.
    the rest of the page contains the code that implements the class. i first use the imports directive, a new feature of visual basic.net, which tells the compiler to import the namespaces. the term "namespace" is a fancy way to refer to the description of a set of prefabricated functionality. it is conceptually identical to a reference in your visual basic 6.0 project. since asp.net will compile this example's code "just-in-time" when a request arrives from a client, i don't have a project in which to set these references, so i have to explicitly add them to the code. the names following imports tell the compiler which sets of functionality to include the references for. in this case, system and system.web.services contain the prefabricated features you need to write a web service.
    the next line defines the name of the class. this class in visual basic is similar to many you've written. you'll see a brand new keyword (inherits) at the end of the line: inherits webservice. this represents one of the main enhancements in visual basic.net—support for the object-oriented concept called inheritance. when you say that your new timeservice class inherits from the webservice class, you are telling the compiler to take all the code from the system-provided class named webservice (known as the base class) and include it in your new timeservice class (known as the derived class). and in addition to reusing the code from the class you inherit from, you can add, alter, and override the functionalities of that class in your new clan. think of inheritance as cutting and pasting without actually moving anything. in fact, seriously deranged c++ and java-language geeks often refer to physically cutting and pasting code as editor inheritance.
    the webservice class is provided by the new .net runtime library, just as many objects used in visual basic 6.0 were provided with the operating system. webservice contains all the prefabricated plumbing required to handle the incoming http requests and route them to the proper methods on your object.
    i'm often asked what the difference is between importing the namespace and declaring inheritance. in other words, what's the difference between the imports and inherits keywords? well, the imports statements only bring in the description of a set of functionality, it doesn't actually make use of it. as i said before, it's like setting a reference. the inherits keyword actually takes part of the code referred to in the description and uses it. it's like dim on steroids.
    now that i've defined my class, i need to define the methods and functions of the class. again, this is very similar to the way it worked in visual basic 6.0, but with one new twist: you have to add a new attribute, <webmethod()>, to every method that you want exposed to web clients. this tells asp.net that the method in which it appears is to be exposed to clients as a web service. you've seen plenty of attributes in visual basic 6.0, such as public, private, and const. the .net framework and visual basic.net use many more of them, which is why there's a new syntax for specifying them. just as your class can contain public and private methods, so can it contain some methods that are exposed to web clients and others that are not.
    finally, let's get down to the internals of the class's method. the handling of the date and time variables in my code may look a little strange to you; it was to me. don't worry about it, it's just how visual basic.net deals with dates and times.


    figure 4 timeservice.asmx in a browser

    now let's access the web service from a client. asp.net contains good prefabricated support for this as well. if you fire up microsoft internet explorer 5.5 and request the asp.net page i just wrote, you will see the page shown in figure 4. asp.net detects the access to the web service page itself (as opposed to one of the methods within the service), and responds with a page of information about the service. this shows you all the methods that asp.net found in the target class (in this case, only gettime), and provides a test capability for each method. enter true or false to tell it whether to show the seconds digits or not, click invoke, and the test page will call the specified method and return the results (if you entered true), as shown in figure 5. note that the parameters are passed in the url, and the results are returned as xml via the get protocol. also note that you must open the page in a way that goes through iis, typing in a qualified utl such as http://localhost/your virtual directory name/timeservice.asmx. if you simply double-click the page in the explorer view of your hard disk, you'll bypass iis and asp.net and simply receive the text of the .asmx page, which isn't what you're looking for.


    figure 5 show seconds

    that's all i had to do to write my web service. it only took 13 lines, counting else and endif. how much easier does it get?

    self-description of web services: the sdl file
    in order to allow programmers to develop client apps that use my web service, i need to provide the information that they need to have during their design and programming process. for example, a client of my web service would probably like to know the methods the web service exposes, the parameters required, and the protocols supported—something conceptually similar to the type library that a standard com component would carry. the problem with type libraries, however, is that they are microsoft com-specific, and you may want non-microsoft systems to be able to consume your web service as well. you may also want to be able to write descriptions of non-microsoft services running on non-microsoft systems, so that your microsoft-built client applications can use these services. what you need is a universal method of describing a service. and you need it to be machine-readable, so that intelligent development environments can make use of it.
    asp.net provides such a descriptive service. when it compiles a web service, asp.net can produce a file listing the protocols supported by the service and the methods provided and parameters required by that service. the file is encoded in xml and uses a vocabulary called service descriptor language (sdl). the sdl file of a web service is sometimes known as its contract because it lists the things that the service is capable of doing and tells you how to ask for them.
    you obtain the sdl file from asp.net by requesting the .asmx file with the characters ?sdl attached to the url. for example, on my local machine, i obtained the sdl file for my sample web service by requesting the url http://localhost/aspxtimedemo/timeservice.asmx?sdl. since i'm not exposing the sample service on an actual running server, i've provided this file in the sample code.
    when you wrote com components in visual basic 6.0 and visual c++&reg; 6.0, you sometimes wrote the component first and then wrote a type library to describe it. other times you started with a type library describing an interface and wrote code that implemented it. sdl can work in both of these ways as well. you could write the code first, as i've done in this sample, in which case asp.net will generate an sdl file for interested clients. alternatively, i could have written the sdl file first, describing what i'd like the service to do, and then use the utility program webserviceutil to generate a template file that implements the service that it describes (similar to the implements keyword in visual basic 6.0).
    the sdl file is somewhat complex, so i've extracted portions to discuss the principles (see figure 6). the servicedescription element is the root of the file. everything inside it is part of the description of this web service. it contains an attribute giving the name of the web service, in this case, timeservice.
    the root contains two interesting types of subelements. the first is a protocol description, which tells an interested client developer which protocols the service supports and how to encode the request and response data for that protocol. i've shown the one for the http get operation, since that's the easiest for me to visualize. any person or development tool looking at the sdl will know that the service named timeservice can be accessed via this protocol. the full sdl file also contains entries saying that it can be accessed via the http post operation and also via the simple object access protocol (soap)—an http/xml hybrid. i discuss http post and soap in the next section of this article. looking inside the protocol description, you can see that the service contains a method called gettime, which lives at the specified url. the request requires a single parameter called showseconds. the fact that it is used in an http get operation implies that it is passed in the form of a string. the response comes back in xml, again in the form of a string.
    the second interesting piece in the sdl file is the w3c-standard <schema> element. this contains the abstract definition of the service, without regard for how it's accessed in any particular protocol or even where it lives. think of this as an interface definition in a type library; it describes a set of methods, but not an implementation of them. you can see that my sample sdl file describes a function named gettime, which requires a boolean parameter called showseconds. you can see that it also contains a separate description of the result of the gettime method, which comes back in a string.

    writing web service clients
    now let's look at what you have to do to write a client that accesses this service. i found writing the clients as easy as writing the service itself. the asp.net listener accepts three different ways of packaging the incoming request into http: http get, http post, and soap. this is conceptually similar to an aircraft control tower speaking three dialects of english— say, american, british, and strine (australian). i'll look at all of these to examine how you would write a client that uses them.

    case 1: http get
    the web service will accept a request through a simple http get request with the showseconds parameter in the url string. you saw the sdl file describing my web services support for this protocol in the previous section. a sample web page providing access to this request is shown in figure 7, and is provided as the file gettimethroughhttpget.htm in this article's sample code. when the request reaches the server, asp.net parses the parameters from the url string, creates the timeservice object, and calls the gettime method.


    figure 7 sample web page

    case 2: http post
    the web service will accept a request through an http post request with the showseconds parameter in an input control. the portion of the sdl file describing my web service's support for the http post operation is shown in figure 8. the separate <request> and <response> elements indicate that making the request of the service, that is, posting the form, is a separate operation from receiving the response. this is how an http post operation normally works, so don't worry about it. the <form> element indicates that the post operation requires a form containing an input control named showseconds, which will carry this parameter. i used microsoft frontpage&reg; 2000 to write a form that does this. a screen shot is shown in figure 9, and the html code in figure 10. the file is provided as gettimethroughhttppost.htm. when the request reaches the server, asp.net creates the timeservice object, pulls the parameters from the form's controls, and calls the gettime method.


    figure 9 sending a request via http post

    case 3: soap
    the web service will accept an incoming call request via an http post request that has all of its information encoded in a soap packet. soap is an xml vocabulary that describes function calls and their parameters. newcomers to soap will probably benefit from reading "develop a web service: up and running with the soap toolkit for visual studio" in the august 2000 issue of msdn magazine, and a young person's guide to the simple object access protocol in the march 2000 issue.
    the portion of the sdl file describing my web service's support for the http post operation is shown in figure 11. i've written a sample program, shown in figure 12, that uses soap to call the gettime method of the web service. it uses the microsoft internet transfer control to do the actual http communication. note that, unlike the previous two examples where the url pointed at the method within the service, soap encoding is directed to the .asmx page containing all the methods of the web service. the soap packet sent to the server contains the name of the function and its parameters, encoded in xml according to an agreed-upon schema, as you can see in the top edit control. when the soap packet reaches the server, asp.net recognizes it, parses the method name and its parameters out of the packet, creates the object, and makes the call.


    figure 12 soap client

    the xml encoding of the request packet varies somewhat from that used by the soap toolkit rob caron discussed in his august 2000 article and the examples that come with it. soap and .net are currently very much under development, so this type of divergence is only to be expected.

    case 4: intelligent soap proxy, synchronous operation
    the soap example from the previous section is obviously quite tedious to write. it reminds me somewhat of manually writing an idispatch client in com, in the sense that there's an awful lot of boilerplate packaging that's critical to get correct (one character off and you're hosed), but which varies little from one method to the next. just as c++ and visual basic-provided wrapper classes that took the pain out of accessing automation objects (many programmers using visual basic never even knew it was painful for the c++ geeks, and the rest either didn't care or actively approved), so does the .net sdk provide the capability of generating wrapper classes that make writing a soap client for your web service a trivial operation.
    the tool that does this is a command-line utility called webserviceutil that comes with the .net sdk. it's also available from visual studio, as described in the september 2000 issue of msdn magazine (see "visual studio.net: build web apps faster and easier using web services and xml"). this program reads the description of the web service from an sdl file and generates a proxy for accessing them from the language you specify. it currently supports visual basic.net, c#, and javascript, but not c++. i copied the sdl file to a local directory and ran webserviceutil with the command line:

    webserviceutil /command:proxy /language:vb /path:timeservice.sdl

    the visual basic-based proxy code is shown in figure 13. it contains both synchronous and asynchronous versions of functions for getting the time from the web service. i'll discuss the synchronous version here, and the asynchronous version in the next section. the proxy class inherits from the base class system.web.services.protocols.soapclientprotocol (you're going to have these long names, so get used to them), which contains the actual code. the proxy class contains a property called path, which the proxy inherits from the base class. this property specifies the url of the server to which the call is directed. it contains a default value that it got from the original sdl file, but the sample program demonstrates how you can change it at runtime if you want. the client calls the named method on the proxy by calling the method invoke, which, again, it has inherited from the base class. this method then creates a soap packet containing the method name and parameters (as shown in the previous section) and sends it to the server over http. when the soap response packet comes back from the server, the base class parses out the return value and returns it to the proxy, which then returns it to the client.
    note that the attributes block in the function name (the characters between the angle brackets) contains information that tells the base class how to package the call, such as the names of methods and parameters. visual studio.net makes extensive use of attributes as a way of passing information to the prefabricated functionality of system code. in earlier days, this would probably have been done through member variables of the base class where it would have been difficult to differentiate immutable runtime attributes from those that can change during program execution. the new arrangement is harder to mess up, which is generally a good thing.
    the actual visual basic-based code for the client is shown in figure 14, and the sample client app is shown in figure 15. you can see that it's pretty trivial. the heavy lifting is done for you by the proxy class.


    figure 15 client app

    case 5: intelligent soap proxy, asynchronous operation
    the internet is much more amorphous and nondeterministic than a single desktop. like disneyland, it can be a lot of fun, but it's almost always so crowded that you have no hope of enjoying it without a clever strategy for managing its chronic overload. even the simplest call to a web service can easily take 5 or 10 seconds to complete, even on a good day with the wind at your back, and can go up to anything from there. you can't leave a user with a frozen interface for more than a second or two, if that.
    you can't make blocking calls to a web service from the thread that handles your program's user interface. an industrial-strength app can't just call the synchronous proxy method from the form button's response function, as i did in the sample. you have to somehow make the call from another thread which can wait for the response without hanging the user interface, and at some later time retrieve the results from that thread and present them to the user.
    until now, most programmers have had to write their own infrastructure code to handle this situation. this type of code is notoriously tricky to get right in all cases, and the time that it took represented a dead loss in monetary terms. now, however, since this situation is nearly universal, the intelligent proxy classes generated by webserviceutil is equipped with prefabricated code to handle it. instead of making a call and blocking until it completes, your program can call one method that transmits the request data to the server and then returns immediately. later, at some convenient time, your program can call another method to harvest the results returned from the server. this makes your life much, much easier because you don't have to write the scheduling code. and it works with any server, not just those that are written to support asynchronous access.
    figure 13 showed both the synchronous and asynchronous versions of the time service call. the proxy contains a method with the name beginmethodname, in this case, begingettime. its parameter list begins with the parameters of the synchronous method, in this case, the showseconds boolean variable. it has two more parameters used in a callback case that is beyond the scope of this article. in the client code in figure 14, i pass nothing (the equivalent of null in visual basic) for both of them. this starts the communication chain, sending out the request, and returning immediately. the return value is an object of type iasyncresult, which i will use in getting the result later. i can now go off and do whatever i want. when testing this in the lab, i inserted a long iterative loop in my .asmx page, just counting from one to a billion to simulate a long operation. you'll have to do that yourself if you want to test this.
    at some later point, if you want to harvest the results of the operation, find out what the time actually was when the server sent it back to you. you do that by calling the endmethodname method on the proxy, in this case, endgettime, passing the iasyncresult that i got from the begin method. that's how the infrastructure code knows which result to give back to you, as the client can have several outstanding requests at the same time. the end method harvests the result and returns it.
    but how do you know when the operation is complete and that the results are ready for you to harvest? the iasyncresult object contains a method used for just this purpose, called iscompleted, which returns true or false. your user interface thread can poll periodically to see if it's done. if you call endgettime before the operation is finished, it will block until the operation does in fact complete. while you probably don't want to do this from your main user interface thread, it may make sense to call it from a worker thread that has reached a point in its processing from which it can't proceed without the results of the web service call.

    web service support in visual studio.net
    the web service example i showed earlier demonstrated that writing web services does not depend on fancy programming environments. but since developer time is the second greatest constraint in software development, it makes sense to write your web services using tools that will help you crank them out faster. since notepad lacks such useful features as an integrated debugger, visual studio.net is a better choice for writing web services. i'll show you how to write a service using the july 2000 pdc release of visual studio.net.
    when you select file | new | project from the visual studio.net main menu, it offers you the dialog box shown in figure 16.


    figure 16 new web service

    i selected visual basic projects in the left pane, the web service icon in the right pane, entered a project name in the edit control, and clicked ok. visual studio.net generated a new solution containing the files shown in figure 17. by the way, the "solution" seems to hold one or more projects, so i really think project group would be a far more descriptive term.


    figure 17 solution explorer

    the interesting programming takes place in the file webservice1.vb, where the code that implements your web service actually lives. the code for my sample web service is shown in figure 18. i've written a bit more code in this one to demonstrate interesting features of the web service environment. it was much easier with visual studio.net than with notepad. if you look at the downloaded sample, you'll find that the figure omits a lot of administrative code placed in the class for the internal use of visual basic.net (users of visual j++&reg; 6.0 will find it familiar). comments in the code promise that it will be hidden in the final release, which will be helpful since it can be very confusing to read.
    the wizard generates several other files, as you saw in figure 17. the file config.web is an xml data file that contains various configuration options that tell asp.net how to handle your web service at runtime. for example, it contains the asp.net session timeout interval.
    the file .disco is an xml data file that is used for controlling dynamic discovery of the web service by clients by collecting sdls and schemas together. the default configuration, which you can see in the downloaded code, simply contains entries that tell asp.net to exclude certain subdirectories (generated in the publishing process) from the sdl file that it generates.
    the .asmx file is the target for client requests. unlike the previous example in which the code lived in this file, this example contains a callout to code that lives elsewhere, as shown here:

    <%@ webservice language="vb"
    codebehind="webservice1.vb"
    class="vs7demotimeservice.webservice1" %>

    the codebehind attribute tells it where to find the code that backs up the service.
    the file globals.vb is where event handler functions live that handle project-wide events, such applicationstart and applicationend. you put your own code in these functions, and asp.net will call it when the specified event takes place. the file globals.asax is the connection between these files and asp.net.
    when you build your project, visual studio.net automatically publishes it to the web server you specify (in this case, the system default). to test the web service, simply start the debugger from the visual studio.net main menu. it opens a testing page similar to the one you saw in figure 4, which is a very smooth way to handle things. you can set breakpoints in your web service and debug anything. the only snag i've found is that the web service doesn't handle bad user input well. for example, if the user puts in a bad value, say, he spells false incorrectly, asp.net rejects the incoming request before it hits your web service and you get the error shown in figure 19.


    figure 19 error report

    intrinsic objects
    the original version of asp contained a set of objects called the intrinsic objects, which represented the connection between an executing asp script and the server on which it was running. this set included the server, application, session, request, and response objects. an asp script could access them directly; a com object used by an asp script had to jump through a few hoops to get them, but could also use them without too much trouble.
    asp.net contains similar objects, generally updated and enhanced. they've also been repackaged to make them easier to use. the intrinsic objects are now part of the system.web.services.webservice base class. when you derive your service from that class, you inherit them for free (i told you that you were going to like inheritance).
    the server, application, and session objects are part of your web service class. they have been updated and enhanced somewhat. for example, the server object now has an htmlencode method, to match its previously existing htmldecode. there is a new object called user, which you will use when performing security authorization (see the section on security). the request and response objects have been moved inside a new intrinsic object called the context (not to be confused with the objectcontext used for committing and aborting transactions—its an unfortunate overloading of the nomenclature). you generally won't use these much, as their functions (accessing properties in the posted form) have been abstracted away by the web service infrastructure. i'll show how to use some of them in the next section.

    state management
    many, many trees have been senselessly murdered in the ongoing debate about stateful versus stateless objects. i won't even attempt to settle the question here. what i will do is to show you the options that are available for state management in a web service, which you can then use to implement whatever state behavior you decide you want.
    web service objects in their natural state (groan) are stateless. that means that asp.net constructs a new instance of that object for each incoming call and destroys it at the end of the call. the result of one call is not available to the next call unless you go out of your way to make it so.
    sometimes this is what you want; sometimes it isn't. for my time service shown in this article, it probably is. what a client wants to show the seconds digit or not has no bearing on what the next client wants or should get. each function call is sufficient unto itself; there's no reason to keep any state from one call to the next. in the classic sense of an object as a combination of data and the code that operates on the data, you might argue that there's no object here. the client is simply making a call that has no relation to anything else, and that's not an object, that's a function. well, tough. i'm going to call it an object because it uses .net object services, and you can't stop me.
    when this behavior isn't what you want, an object can maintain state between one call and another. the object is still created and destroyed on demand, but it can use asp.net to hold data that it was working on in its previous life, as you might leave instructions in your will for your descendants. asp.net can maintain two types of state in a web service: application state and session state. the former is available to all parts of your internet application; that is to say every session with every user in that object and all the others built into your solution. (see what a lame word solution is? try substituting project group. better, no?) the latter is available only to the session of the individual user currently connected to it. a session is a time-limited conceptual connection maintained by asp.net to make it easier for you to program behavior on a per-conversation basis. you use session state for remembering things like the items in a particular user's shopping cart, so you'll probably use it much more often than application-level state.
    the asp.net system on which the web service is based provides a mechanism for maintaining and tracking state variables. the base class webservice from which your web service derives contains two collections for holding state, one called application and one called session. you can put data into them and take data out by accessing them through string names of items. the sample service shown in figure 18 contains code that uses both types of state. i keep the total number of requests in the application, and the number of requests for this particular user in the session-level state.

    security in web services
    security is vital to any type of distributed programming, and discussions of it are often highly charged with emotion. i will attempt to outline the problems that arise in this area, and discuss how asp.net provides your web service with prefabricated functionality that allows you to get the level of security you need without too much trouble. but a full-scale discussion of security would take two or three full articles.
    all web services care about security, whether you think they do or not. you might think that my sample time service doesn't, because i don't care who sees the timer. i still want to make sure that no one deletes it or hacks the code to make it subtract ten minutes from the current time and make all the callers late for their appointments. so i want read permission for anyone, and write permission only for a select few. iis provides that basic level of security.
    the security requirements of a web service are somewhat like those of a city hall. you have large numbers of people coming and going anonymously, accessing areas such as the tourism office that dispenses maps one at a time. but other areas of the same city hall, such as the floor containing the mayor's office, don't allow anyone in who cannot prove his identity (authentication) and who doesn't have business on the floor (authorization).
    the first problem in security is authentication—who are you, and how do i know you really are that person? you can't figure out if this person or that one is allowed to access some resource until you know who they are. asp.net gets its authentication service from the underlying iis layer. you use the existing iis tools to mark particular pages as requiring authentication, as shown in figure 20, clearing the anonymous access box as shown. iis will then require a user id/password handshake before allowing the user to view the specified page. this requires that the user have an account accessible to the server. if the authentication succeeds, the asp.net script is run using the identity of the authenticated user.


    figure 20 authentication methods

    when writing a .net proxy-based client application (as shown earlier) the proxy base class contains properties called username, password, and domain. setting these properties, both strings, allows a client to easily pass them to a server that requires them.
    obviously, authentication requires extra network traffic, so you should only use it when needed. the city hall tourist office wouldn't be very useful if it required ids and strip searches to obtain a map. my sample doesn't require authentication just to read the page, only to write it. in this case, the administrator leaves the anonymous access box checked and specifies the identity of the account that any anonymous client will use for its access checks on the server. generally, this account has a low level of privilege.
    once you've decided who the user is, you need to check before performing any sensitive action whether that person is or isn't allowed to do it. sometimes this is handled by the back end operating system. for example, ntfs allows an administrator to set access permissions on files, and you hope that administrator won't allow anonymous users access to system configuration files. other programs, such as microsoft sql server&#8482;, do similar things.
    it's usually best to perform authorization checks as early in the access process as possible, so that if they fail, you've wasted the minimum amount of processing time. your web service object can perform its own authorization via the intrinsic object named user. this contains a method called iscallerinrole, which will tell you whether the user is a member of an administrative group you've set up elsewhere. it is conceptually identical to the similar method seen in com+. if you want to go deeper, you can use the identity property of the user object. this returns an iidentity interface, which tells you the user name and authentication mechanism used to verify that user name. you can write your own code that uses that information to decide if the user is allowed to do this or that.
    web services will, at some future time, support passport authentication and cookie-based authentication, which would make many lives easier. that is beyond the scope of this article.

    conclusion
    all programmers would like to write programs that talk to each other over the internet, no matter what type of system they're running on. you can accomplish this by settling on the lowest common denominator of xml and http. the web services portion of the microsoft .net technology suite makes it easy for you to write your business logic in the form of .net components and expose them to all web clients that speak http get, http post, or soap. that's just about everyone in the world. an sdl file, also generated by the web services infrastructure, provides a machine-readable description of the functionality available through the web service. a proxy generator provides function-based access to a web service, making it easier to write client programs. visual studio.net provides a productive environment for developing web services. the web service infrastructure provides several options for setting up the security required by a web app. these tools allow you to write better internet applications much more quickly—a good combination.


    --------------------------------------------------------------------------------
    for related articles see:
    visual studio.net: build web applications faster and easier using web services and xml
    p2p: writing peer-to-peer networked apps with the microsoft .net framework


    --------------------------------------------------------------------------------
    david s. platt is president and founder of rolling thunder computing inc. he teaches com and com+ at harvard university and at companies all over the world. he publishes a free e-mail newsletter on com+, available at http://www.rollthunder.com. david is the author of understanding com+ (microsoft press) and an upcoming book introducing the microsoft .net platform, due in spring 2001 (microsoft press).

    --------------------------------------------------------------------------------


    from the february 2001 issue of msdn magazine.
    get it at your local newsstand, or better yet, subscribe.



    back to top
    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表