quick overview of asp.net sessions
asp.net session state is maintained by using one of two underlying mechanisms. the first is by using http cookies. the idea behind http cookies is that when the client sends a request, the server sends back a response with an http set-cookie header that has a name/value pair in it. for all subsequent requests to the same server, the client sends the name/value pair in an http cookie header. the server then can use the value to associate the subsequent requests with the initial request. asp.net uses a cookie that holds a session id to maintain session state. then that id is used to find the corresponding instance of the httpsessionstate class for that particular user. the httpsessionstate class provides just a generic collection in which you can store any data that you want.
the other mechanism that asp.net uses for maintaining session state works without cookies. some browsers do not support cookies or are not configured to keep and send cookies. asp.net provides a mechanism for getting around this problem by redirecting a request to a url that has the asp.net session id embedded in it. when a request is received, the embedded session id is simply stripped out of the url and is used to find the appropriate instance of the session object. this works great for browsers that are doing http get requests, but creates issues when writing microsoft® .net code that consumes an xml web service.
it should be noted that sometimes it makes sense to store state information in cookies themselves instead of in the asp.net session object. by avoiding the session object, you use fewer resources on the server, and you do not have to worry about issues like locating a specific instance of the session object across a web farm, instances of the session object being cleaned up because of a long delays between requests, or session instances lingering around for no reason until their timeout period expires. however, if you have data that includes implementation information that you do not want to share with the consumers of your service, or is private data that you do not want to send across an unencrypted channel, or if the data would be impractical to serialize into an http header, then it may make sense to take advantage of the httpsessionstate class in asp.net. the httpsessionstate class returns an index key that is used to map a particular user to an instance of the httpsessionstate class that holds information stored for that user. both the asp.net httpsessionstate class and http cookies are available to users writing asp.net web services.
why use an http mechanism for maintaining state in an xml web service?
there are many ways to maintain state between soap requests. certainly one feasible option would be to include something like the asp session id in the soap header of your soap message. the problem is that you have to: 1) still write the server side code yourself, and 2) make sure your clients treat your session id header like an http cookie and send it back to you with each request. there are certainly cases where using the soap header approach makes a lot of sense, but there are situations where using the http approach can make sense as well.
asp.net session state is already done for you. the httpsessionstate class is available for easily storing your session objects. most http clients already understand that they must return the cookies that are set by the server and httpsessionstate happens to support the underlying transport most frequently used for soap communications—http. thus it makes sense that using asp.net session support could be a smart decision to meet many state management requirements.
enabling session support on the server
by default, asp.net session support for each web method is turned off. you must explicitly enable session support for each web method that wants to use session state. this is done by adding the enablesession property to the webmethod attribute of your function. the code for a web method with the enablesession property set to true, and which accesses the httpsessionstate object, is shown below.
<webmethod(enablesession:=true)> _ public function incrementsessioncounterx() as integer dim counter as integer if context.session("counter") is nothing then counter = 1 else counter = context.session("counter") + 1 end if context.session("counter") = counter return counter end function
as you might expect, if you enable session support for one web method, that does not imply that it is enabled for another web method. in fact, the context.session property will be null if enablesession is not explicitly set to true for a particular web method.
be aware that it is possible to disable sessions by way of a web.config setting, so that even if you use the enablesession property in your webmethod attribute, context.session will always be null. the /configuration/system.web/sessionstate element has a mode attribute that is used to configure how session state is maintained for your asp.net application. by default the mode is set to "inproc," which means that the httpsessionstate objects will simply be held in the asp.net process' memory. if the mode is set to "off," then there will be no session state support in the asp.net application.
from the http server standpoint, the scope of an asp.net session is that it lives within a given asp.net application. this means that the same instance of the httpsessionstate class will be used for all session-enabled asp.net requests within a single virtual directory for a particular user. a request to a different virtual directory with the same session id cookie will result in asp.net being unable to find the corresponding session object—because the session id was set for a different asp.net application. asp.net does not differentiate between aspx and asmx requests as far as sessions are concerned, so you could theoretically share session state between a web method call and a normal aspx file. however, there are client-side issues that we will look at in a little bit that might make this tricky.
when setting an http cookie, you can associate an optional expiration time with it. the expiration time indicates how long the client should continue sending the cookie back to the server. if a cookie is set without the optional expiration, it will only be returned for the life of the process making the requests. for instance, microsoft® internet explorer will return the cookie until you close that particular instance of your browser. the session id cookies used by asp.net do not have expiration times. therefore, if multiple processes on a client machine are making http requests to your server, then they will not share the same httpsessionstate object. this is true even if the two processes are running at the same time.
if you are making simultaneous web service calls from the same process, the requests will be serialized at the server so that only one will execute at any one time. unlike .aspx pages that have support for read-only access to the httpsessionstate object, which allows for simultaneous processing of multiple requests, there is no such capability with asp.net web services. all web method calls with sessions enabled have read/write access and will be serialized within each session.
client-side issues
successfully using the httpsessionstate capabilities in your web service does rely upon some assumptions about the consumers of your web service. first and foremost, if you are using the default http cookie mode of maintaining session state, then your clients must support http cookies. if you are using the cookieless mechanism for supporting sessions, then your clients must be able and willing to redirect their requests to the modified urls with the session ids in them. as it turns out, this is not a trivial assumption, even with a .net client application.
everything works from the browser
if you develop an asp.net web service in microsoft® visual studio® .net, the default debugging behavior is to launch internet explorer and browse to your .asmx file. this usually will result in a friendly html interface for invoking your web methods. this turns out to be a nice way to debug your web service code, and if you have set the enablesession property to true for your web method, it tends to work out beautifully. even if you turn on cookieless session support, the browser client will work perfectly, and your session will work in the manner that you expect it to.
however, most web service requests do not come from a browser. what happens when you create a client application that uses the "add web reference" feature of the .net framework? let's take a look at the results.
problems using add web reference
i created a simple xml web service using the code snippet that we saw earlier. if you recall, the web method is called incrementsessioncounter and simply stores an integer in the httpsessionstate object, increments it with each call, and returns the current value. from the browser client, we see that the number increases by one with each invocation as we expect.
next, i created a simple microsoft® windows form application and added a web reference for my web service. the code for invoking my web service looks like this:
' does not work with asp.net sessionsprivate sub button1_click(byval sender as system.object, _ byval e as system.eventargs) handles button1.click dim proxy as new localhost.service1() dim ret as integer ret = proxy.incrementsessioncounter() label1.text = "result: " & cstr(ret)end sub
when i invoke the web service the first time, everything works as expected. the web method returns the initial value for my session variable, which is 1. now if i click on button1 to invoke my web method again, i expect to see a returned value of 2. however, no matter how many times i click on button1, i always see a value of 1 returned.
you might suspect the cause of this is that i'm creating a new instance of the proxy class for my web service, so each time i click on the button, i am losing my cookies (so to speak). unfortunately, even if you move the proxy initialization code into the constructor for your form class and use the same instance of the proxy for each web method call, you still will not see the session variable return with a value greater than 1.
the problem is with the cookies. the web service code does not see a valid session id with the request, so it creates a brand new httpsessionstate object for each call, and returns the initial value of 1. the reason for this is that the client proxy class, which inherits from the system.web.services.protocols.soaphttpclientprotocol class does not have an instance of the system.net.cookiecontainer class associated with it. basically, there is no place to store cookies that are returned. to fix this problem, i changed my code as follows with the new code highlighted:
' works with cookied asp.net sessions but not with ' cookieless sessions.private cookies as system.net.cookiecontainerprivate sub button1_click(byval sender as system.object, _ byval e as system.eventargs) handles button1.click dim proxy as new localhost.service1() dim ret as integer ' set the cookie container on the proxy if cookies is nothing then cookies = new system.net.cookiecontainer() end if proxy.cookiecontainer = cookies ret = proxy.incrementsessioncounter() label1.text = "result: " & cstr(ret)end sub
and now the code works as expected! with each click of button1, i see the returned value increase by 1. note that the cookies variable is not declared inside my function. it is a private member of my form class. i need to use the same instance of the cookiecontainer class with each request if i expect the same session id cookie to be returned to the server. this explains why a default cookie container is not automatically associated with an instance of the soaphttpclientprotocol class. there is a good chance that you would want to use a separately managed cookie container that could be shared among multiple instances of the soaphttpclientprotocol class, instead of automatically creating a new cookie container for each instance.
cookieless sessions
from the standpoint of the web service developer, you might think that quite a few people trying to consume your service will forget to add a cookie container to their client proxies. with a clever twinkle in your eye, you also might think that cookieless sessions may be the perfect solution to this problem. if you set the cookieless attribute of the sessionstate element to "true" in your web.config, you will notice that sessions still work perfectly when invoking your web methods using the browser interface. unfortunately, there are still issues if you use the "add web reference" capabilities within visual studio .net.
to investigate cookieless sessions, i decided to take the client code i used above and simply see if it would work for a web service that was configured for cookieless sessions. i did not bother to delete the cookie container code, because i wanted to have code that would work with traditional cookied sessions as well as cookieless sessions. being a bit of an optimist, i simply ran the code as is. disappointingly, but not completely unexpectedly, i witnessed the following exception:
an unhandled exception of type 'system.net.webexception' occurred in system.web.services.dlladditional information: the request failed with the error message:--<html><head><title>object moved</title></head><body><h2>object moved to <a href='/httpsessionstate/(l2z3psnhh2cf1oahmai44p21)/service1.asmx'>here</a>.</h2></body></html>
what happened is that the http request received a response that was not a "200 ok" http response. for those of you familiar with http, you probably can correlate the html listed in the response shown as indicating that this was a "302 found" http response. this means that the request was redirected to the url indicated in the hyperlink. the html returned is actually just a nice thing that a browser can show if for some reason it does not support redirects, or until the redirected request completes. if you look at the hyperlink, you will notice that the href includes an interesting substring of "(l2z3psnhh2cf1oahmai44p21)". if you have been paying attention, you have probably correctly deduced that this is the asp.net session id, and it has been embedded in the url that we have been redirected to. what we need is for our client proxy class to resend the request to this new url.
having done more than my share of programming with the old win32 wininet api, i went looking for a property on our proxy class that would allow me to turn on auto redirects. in layman's terms, this simply means that if we received an http response of "302 found," we would simply resend the request to the url indicated by the http location header in the response. i was feeling pretty smart when the microsoft® intellisense® in visual studio .net showed me the allowautoredirect property on my proxy class. i quickly added the following line to my code:
proxy.allowautoredirect = true
i gave my program another try, thinking this was still slightly easier than creating a cookiecontainer class, and assigning it to my proxy. i got the following exception (truncated for brevity):
an unhandled exception of type 'system.invalidoperationexception' occurred in system.web.services.dlladditional information: client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.the request failed with the error message: ã‚â…
if you looked at the contents of the error message, you would find that you were looking at the html page that you see when you browse to your .asmx file. the question you might have is: why it is returning html when i am posting xml (in the form of a soap envelope) to the web service? as it turns out, you did not send an http post request with a soap envelope, you simply sent an http get request with no body, and your web service appropriately assumed you were a browser and returned its normal html response. how could this happen?
if you read the http specification, you will find that it is appropriate for an http client to send an http get request to the indicated url in reaction to an http "302 found" response, even if the initial request was an http post. this works great with browsers, because just about all of their requests are http get requests in the first place. it does not work well when you see this result when you are posting data to a url.
the justification for this is that potentially sensitive data may be contained in the posted data, so you need to confirm with the user if they really want to send the data to the new resource. if you are going to the new location based off an auto-redirect setting, you are obviously failing to confirm with the user whether it is okay to post their data to a new location. therefore the data is not sent, and a simple http get request is sent instead.
i made the following modifications to set the uri on the proxy, catch the "302 found" webexception, prompt the user for permission to redirect their request, and call my function again with the new location (changes from the previous code are highlighted):
' works with both cookied and cookieless asp.net sessions.private cookies as system.net.cookiecontainerprivate webserviceurl as uriprivate sub button1_click(byval sender as system.object, _ byval e as system.eventargs) handles button1.click dim proxy as new localhost.service1() dim ret as integer ' set the cookie container on the proxy if cookies is nothing then cookies = new system.net.cookiecontainer() end if proxy.cookiecontainer = cookies ' set the url on the proxy if webserviceurl is nothing then webserviceurl = new uri(proxy.url) else proxy.url = webserviceurl.absoluteuri end if try ret = proxy.incrementsessioncounter() catch we as webexception ' we need an httpwebresponse if we expect to ' check the http status code. if typeof we.response is httpwebresponse then dim httpresponse as httpwebresponse httpresponse = we.response if httpresponse.statuscode = httpstatuscode.found then ' this is a "302 found" response. prompt the user ' to see if it is okay to redirect. if msgbox(string.format(redirectprompt, _ httpresponse.headers("location")), _ msgboxstyle.yesno) = _ msgboxresult.yes then ' it is okay. set the new location and ' try again. webserviceurl = new uri(webserviceurl, _ httpresponse.headers("location")) button1_click(sender, e) return end if end if end if throw we end try label1.text = "result: " & cstr(ret)end sub
and now the asp.net session code works as expected. for the purposes of your own application, you can determine whether you need to prompt a user for redirecting their http post request or not. for instance, if you were calling this code from a service, you would not want to create a dialog that could not be seen.
this may seem to be a lot of work for getting asp.net sessions to work properly, but be aware that the code shown is useful for other things as well. for instance, any web service on any platform that uses http cookies would require the cookie container code. similarly, there may be a host of other reasons why you might receive a "302 found" response in reply to your request to a web service. in a robust application, there will probably be a number of special scenarios that you will want to handle when invoking a web service. handling cookies and redirects are two such scenarios you may want to include in your web service invocation code on a regular basis.
conclusion
asp.net sessions can be very useful for maintaining state between web method calls in your web service. you do need to be aware that there may be issues that must be handled by client applications that you may not see when testing your web service with the convenient browser interface. fortunately, these issues are not particularly hard to handle.
新闻热点
疑难解答
图片精选