Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ASP.NET Cookieless Sessions and JQuery AJAX to play together nicely

I have a web site that uses JQuery AJAX. With this JQuery code

$.post("/ajax/getsomedata.aspx", {'id': id }, 
    function(data) 
    {
        dosomething(data);
    }
);

When I run this with cookieless="false", id shows up in Request.Form. When I set cookieless="true", id is no longer in Request.Form.

UPDATE, What I did

I added a call to Response.ApplyAppPathModifier() to preserve the data and avoid an automatic redirect. I am excepting **Diago(( and deleting my own because his references give some insite into what's going on. I like to idea of the seperate domain, but I can't do that here.

Here's the updated code:

$.post("<%=Response.ApplyAppPathModifier("/ajax/getsomedata.aspx")%>", 
        {'id': id },
    function(data)     
    {        
        dosomething(data);    
    }
);

According to MSDN Response.ApplyAppPathModifier() adds the session id if you are in cookieless session state, and returns the unaltered URL if you are not.

Since there is no session id, ASP.NET creates a new session and does a redirect (thus stripping off any form data).

like image 535
jrcs3 Avatar asked May 15 '09 15:05

jrcs3


2 Answers

I struggled with the same problem recently. This is one of the four drawbacks of using cookieless sessions. The request is rewritten when hitting the server and the request variables are dropped. This can be extremely painful when using WebServices and POST request using ASP.Net. This works fine when using GET.

You will have a similar problem using normal post. There is an article here that explains how it can be done. This MSDN article also discusses the drawbacks at length.

The best solution is to put your services on a seperate domain or IIS Virtual site not using cookieless sessions.

Using Forms Authentication with cookieless sessions is also an interesting challenge.

like image 108
BinaryMisfit Avatar answered Nov 15 '22 01:11

BinaryMisfit


I wasted my whole day to sort this problem out, while this is just a quick fix.

During the PageMethod call, the session id is not being passed with the request URL, so a new session_start event is getting fired. We just need to set the exact request path before calling a pagemethod, so that the new session start event will not be fired.

if ('<%= HttpContext.Current.Session.IsCookieless %>==True') {
    //need to pass session id in request path
    PageMethods.set_path('<%= System.Web.Configuration.WebConfigurationManager.AppSettings("WebRoot") %>(S(<%=Session.SessionID%>))/secure/PageName.aspx');
}
PageMethods.PageMethodName(param1,param2, CallSuccess, CallFailed);
like image 24
Krishan Kumar Gaurav Avatar answered Nov 15 '22 01:11

Krishan Kumar Gaurav