I 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.