ASP.NET Access current session using jQuery - asp.net

Is there a way to modify the current Session() variable using jQuery? If it involves deconstructing the ViewState then I'm not really interested. Just curious if there was some easy way to do it.
Thanks!

If you need to pass a per session property between jQuery and the server you could try using cookies instead.
Otherwise you'll have to create a custom handler (ashx) file or a WebMethod or similar that lets you access it with Ajax calls.

jQuery
$.get("http://somewhere/page.aspx",
{sessionVar: "something"},
function(data)
{
alert("Session(\"something\") = " + data);
}
);
page.aspx:
Response.Write(Session[Request.QueryString["sessionVar"]]);
That's with no error checking or anything...

Session is stored on the server and you can't access it from jQuery unless you make an ajax call and get the session details from server.
Other than the fact that both ViewState and Session helps developer maintain state in their web application, they have nothing to do with each other.
EDIT:
If you want to modify the session using Ajax. Create an HTTP handler SessionHelper.ashx. This session handler can take 'SessionVariableName' and 'SessionVariableValue' as Query String parameters and modify the session state on the server. You can call this handler from jQuery using $.ajax method.
Please keep in mind that if you expose an handler like that, you will have to protect it against misuse as any person can call the handler directly and modify the Session variables. [e.g. If you store User role/privileges in session, a hacker can modify this role/privileges through this handler.]

Related

asp how to get the current page reference from a web service method?

i'm in a slideshow extender web service method and trying to get a stringfrom the request.QueryString that i got in page_load.
of course new myPage() won't do.
so what can i do?
thanks
You can store the querystring in the Session on page load and access it from your service when necessary.
You can store the applicable parts of the query string in a hidden field on the page and pass the values along as part of your service call.
If the querystring is still a part of the URL when you want to make the service call, you can extract the values from the url with javascript and pass them along.

Call an asp.net page (ashx handler) from a different asp.net page

I have a admin page in asp.net that adds data to a database. This database is available as a JSON string to external websites, however, since it's a lot of data, the external websites cache this data locally.
I want to be able to ping the external websites to let them know the data has changed so they can referesh their cache. I figure I can setup an ASHX handler that receives a parameter telling them what data has changed, so they can both delete that data and refresh it.
The only part I'm not sure about is the best way to call this external page from my admin page. Do I just do a regular WebRequest and discard the result? or is there a simpler way to call a page from code when you don't need the response?
Basically I just want to "ping" this page, so it knows it needs to refresh.
thanks!
If you just want to call the remote page, you can use the WebRequest class.
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
WebRequest request = WebRequest.Create("http://my.domain.ext/page.ashx");
using(WebResponse response = request.GetResponse()) {
response.Close();
}
If you want to do more advanced stuff a webservice would be more appropriate.
You could have a flag set up in the database. That would turn this into a much simpler task.
If no alternative exists you can use the WebClient class:
using (var wc = new WebClient())
{
wc.DownloadString(address);
}

asp.net ajax calls to user controls

When calling page methods or web services with either jquery or MSAjax, the Session object appears to be null so Im finding it hard to track users who execute them.
Seeing that the session id is sent with the cookie on each request, is it possible to obtain the session object from somewhere?
You can enable the session in your WebMethod attribute like so.
[WebMethod(EnableSession = true)]
This should enable you to access the Session object.

ASP.NET global events

which event is the most suitable to check for Session expired? i'm trying to trap each server request, and if Session is null, redirect to a different page.
You can determine if a new session is being created by hooking Session_OnStart - http://msdn.microsoft.com/en-us/library/ms178583(VS.80).aspx
You can handle the Session_OnStart
event by adding a subroutine named
Session_OnStart to the Global.asax
file. The Session_OnStart subroutine
is run at the beginning of a request
if the request begins a new session. A
new session will be started if a
request is made that does not contain
a SessionID value or if the SessionID
property contained in the request
references a session that has expired.
This will tell you effectively when a new session is being created, regardless of if the user just arrived or the session had expired.
It would be hard to reliably differentiate between both scenarios. I guess you could try to get a hold a the session id in the either the session cookie or embedded in the url (cookieless), but you would need to check it before getting to the above event, and later check whether the request had a session id originally. Check if you can get to the session id in the cookieless version, because it is stripped out of the urls asp.net gives you (not sure if early in the lifecycle you get to see it).
This is often best achieved by using a base Page class for all otehr classes, and implementing this in the Page_Load method.
Use BasePage class, which inherits from Page class. Let every aspx page inherits that BasePage class. In BasePage class, override OnInit event, in which you can check for Session or Cookie, and redirect user to login page (for example).
I use this approach for all mine webforms apps, because it's easy to implement and use.

Extending Forms Authentication Timeout When Making AJAX Calls With jQuery

I'm looking to rewrite a pretty intensive CRUD type ASP.NET page to utilize ajax calls (specifically jQuery ajax). My concern in doing this is that the user may be on this page longer than the forms authentication timeout. Because of this, I'm thinking that I should extend the forms authentication ticket with each ajax call (basically how it does in a normal web forms submit model). So the questions:
Is this even a valid concern? If so, would writing a jQuery plugin to extend the forms authentication timeout be possible? Does one already exist? Would using ASP.NET AJAX be a better approach?
Any comments\help would be appreciated.
I can confirm that making a web service or page method call through jQuery will extend an ASP.NET session expiration in the same way that a regular postback will.
I often use a five minute setInterval() to call a "keep-alive" service, which will preserve the user's session indefinitely even if they leave the application idle.
You should be able to use MS Ajax without the Script manager and use jQuery to consume the WebMethods. More info doing so here
As far as I know, calling a WebMethod will extend the user's session timeout. So this approach may be a best of both worlds.
I use this for my keepalive webservice.
Modify this to your liking and let me know if it works...
Note: session("UID") is a variable I setup at login. I name my ticket the same
<WebMethod(CacheDuration:=0, EnableSession:=True)> _
Public Function keepSessionAlive() As String
If Session("UID") Is Nothing OrElse Session("UID") = 0 Then
Throw New ApplicationException("Login")
End If
Session("lastKeepSessionAlive") = DateTime.Now
If Not (Context.Request.Cookies(System.Web.Security.FormsAuthentication.FormsCookieName) Is Nothing) Then
Dim ticket As System.Web.Security.FormsAuthenticationTicket
Try
ticket = System.Web.Security.FormsAuthentication.Decrypt(Context.Request.Cookies(System.Web.Security.FormsAuthentication.FormsCookieName).Value)
If ticket.Name = Context.Session("UID") Then
System.Web.Security.FormsAuthentication.SetAuthCookie(Context.Session("UID"), False)
Debug.WriteLine("keepAlive:AuthenticationReset")
End If
Catch ex As Exception
Debug.WriteLine("keepAlive:AuthenticationReset FAILED!!!")
Throw New ApplicationException("Login")
End Try
Else
Debug.WriteLine("keepAlive.Load: No Authentication Cookie. Error")
Throw New ApplicationException("Login")
End If
Return Session.SessionID.ToString
End Function
Use Fiddler or some other utility to see if Microsoft was smart enough to make sure the cookie gets updated between AJAX calls. You may have better luck (with regard to automatic updating of the forms auth tickeet) if you use Microsoft's baked-in asp.net AJAX (which is substantially similar).
Forms auth works via a cookie. Cookies are sent with XMLHttpRequest requests, so I don't think there's a problem here.
Note that there is an issue related to the FormsAuthTicket expiring, and being forced to redirect to login.aspx or some such. But that's an entirely different scenario than what you're talking about.
I don't think I completely understand what it is you're asking but in terms of the jquery ajax timeout, you can set the local timeout in the ajax call.
Example:
$.ajax('ajax.php',{timeout: 60000},function (data) {
alert(data);
}

Resources