Cookieless Session with ASP.NET Ajax and Web Services
July 4th, 2007I just discovered a little snag when calling session-enabled ASMX web services from ASP.NET Ajax using cookieless session tracking (hat tip to Guy Barrette for raising the issue). Here’s the scenario: You are using cookieless sessions and want to call a web service in the same web app from JavaScript code. With cookieless session state, you get a URI like this for your web page:
/AJAXFuturesEnabledWebSite3/(S(d0xa1fqpupjt1uactajufoan))/default.aspx
The URI for the web service would then look like this:
/AJAXFuturesEnabledWebSite3/(S(d0xa1fqpupjt1uactajufoan))/WebService.asmx
You can add an ASP.NET Ajax service reference to the web service declaratively in the <asp:ScriptManager> control or programmatically like this:
ServiceReference sr = new ServiceReference(”WebService.asmx”);
ScriptManager1.Services.Add(sr);
The reference is using a relative path so everything should be fine since default.aspx and WebService.asmx are both at the same location.
If you look at the source of the resulting web page, you’ll find a script tag that is pulling down a JavaScript definition for a proxy to be used to call the web service:
<script src=”WebService.asmx/js” type=”text/javascript”></script>
The script tag is using a relative path so everything should still be fine. But if you try to call the web service from JavaScript, it doesn’t work:
Take a look at the script produced by WebService.asmx/js (click image to enlarge):
The second-to-last line sets the path to the web service without including the session ID in the URI:
WebService.set_path(”/AJAXFuturesEnabledWebSite3/WebService.asmx”);
You can work around this by resetting the path to the web service yourself. For example, the following works:
function CallService()
{
ws = new WebService();
WebService.set_path(”WebService.asmx”);
ws.HelloWorld(SucceededCallback);
}
Alternatively, you can invoke the web method using WebServiceProxy.invoke():
Sys.Net.WebServiceProxy.invoke(’WebService.asmx’, ‘HelloWorld’,
false,{}, SucceededCallback, null,”User Context”,1000000);
I prefer the first approach. In both cases you are explicitly providing the URI for the web service because the generated proxy object does not include the session ID in the URI.


August 7th, 2007 at 6:52 am
Good work!! Thanks a lot.
August 21st, 2007 at 2:09 pm
Man, been 2 days around that! Nice job!!!
January 23rd, 2008 at 1:53 pm
Awesome! Now it works without Cookies, thank’s a lot!
January 28th, 2008 at 8:32 am
Many thanks man!!!! Saved me few hours of researching.
September 25th, 2008 at 2:29 am
you saved my ass!
October 14th, 2008 at 10:55 am
YOU SAVED MY ASS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Dude,you rock.you have no idea how much i suffered trying to get this!!!!!!!!!!3 days in a stand still!!!dude. THANK YOU!!!
October 20th, 2008 at 5:24 am
I’m with Vuyani, thanks :)
June 23rd, 2010 at 12:57 pm
You are amazing, thank you so much for this post! This helped a lot :)