Clearing a session in ASP.NET - asp.net

I'm a new developer, and I've been assigned the task of figuring out why our log out function is not working. I've tried every possible method I can find. Below is the log I've kept that includes the methods I've used.
Added a log out button to the CommonHeader.ascx form
Have tried numerous methods in the logout.aspx.vb form to get it to end or clear the session but none of them work.
a. ClearSession sub routine defined in the logout.aspx.vb form:
Session("Variable") = ""
FormsAuthentication.SignOut()
Session.RemoveAll()
Session.Abandon()
Session.Clear()
b. Also added this to the top of the Page_Load sub routine:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
HttpContext.Current.Response.Cache.SetNoServerCaching()
HttpContext.Current.Response.Cache.SetNoStore()
c. Also changed the ClearSession sub routine to Session.Contents.Remove("Variable") from Session("Variable") = ""
None of these methods work. We use Siteminder, and I've been wondering if this is the root of the problem. I just can't find anything on clearing a Session that uses Siteminder. Also keep in mind this application is coded with Visual Studio 2003.
This is the code for the button I'm using in the ascx file:
athp:TopNavText Title="Log Out" NavigateUrl="logout.aspx" Target="_top"/
Then on the "logout.aspx" form I've tried just using one of the methods described above or a combination of each one. This is the code before I ever touch it:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ClearSession()
Response.Redirect("login.aspx")
End Sub
Public Sub ClearSession()
Session("Variable") = ""
End Sub

Finally figured out the solution, I originally did not define the domain upon deletion of the cookie which contained the siteminder session id. The code I used is as following:
Dim cookie3 As HttpCookie = New HttpCookie("SMSESSION", "NO")
cookie3.Expires = DateTime.Now.AddYears(-1)
cookie3.Domain = ".domain.com"
Response.Cookies.Add(cookie3)
Response.Redirect("login.aspx")

This question: formsauthentication-signout-does-not-log-the-user-out describes a problem with not clearing cookies even after calling FormsAuthentication.SignOut(). This sounds like your issue, they say it's a bug with .NET and as your using 1.1 this sounds distinctly possible.

HI friend please add the click event of the button in user control. And in the click event please add the following code and remove all the other code.
Session("Variable") = "";

look at this post
C# Clear Session
Whether its c sharp or vb the same rules still apply. You are calling session abandon then clear, but by the time you call clear the session should be gone anyway.
Clear keeps the session state along with the objects in it, so by calling it after abandon you could in fact be reinitializing a session for the user, but with cleared variables.
See this post for the order and proper way to kill the session and redirect to the login page if you have one
FormsAuthentication.SignOut() does not log the user out

The first thing to note is that, if you're using Forms Authentication, Session has absolutely nothing to do with whether or not a user is logged in.
Calling FormsAuthentication.SignOut will remove the forms-authentication ticket information from the cookie or the URL if CookiesSupported is false.
But it will have no effect on what is stored in Session.
UPDATE
Why do you think log out (FormsAuthentication.SignOut) is not working? What are you expecting to happen when you click on Sign Out, and what exactly is actually happening?
I'd get rid of all the code to clear Session and look at this. For example, look at the http traffic with a tool such as Fiddler: you should be able to see that the FormsAUthentication cookie is removed when you click on Log Out.

Related

IE Session.Abandon()

IE seems a bit buggy when it comes on Abondoning the session. This is the whole code thats get executed:
Protected Sub logout_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Session.Abandon()
Response.Redirect("login.aspx")
End Sub
It redirects to login.aspx but when i change the url to default.aspx its get in without checking it. In all the other browsers it doesnt and get you redirected because of the following code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If (Session("Naam") Is Nothing) Then
Response.Redirect("login.aspx")
Else
Label1.Text = "Welkom " + Session("Naam").ToString()
End If
End Sub
Is there any reason that IE doesnt abandon the session?
note//
I am not using log-incontrol what so ever
Try disabling/removing the autopostback and then re-test your page. I would guess that the autopostback is somehow keeping your session data active,maybe its being used in the postback? therefore all instance's dont get abandoned?.
Edit
When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was destroyed with the previous Session object when the page containing the previous example finished processing.
The server creates a new Session object when you open a subsequent Web page, after abandoning a session. You can store variables and objects in this new Session object.
The above is from the MSDN website.
Which all means that somewhere your session object is being used AFTER you have abandoned it.
I normally use the same code block as you do to log a member out of a session.
Session.Abandon()
Response.Redirect("default.aspx")
with the same code in the global.asax or global.aspx file too.

.NET Master Page Session state variable not saving

I'm trying to store the session state in a master page to keep track of the previous URL. Here's what I'm doing
Public Property PreviousPage() As String
Get
Return Session("theprevpage")
End Get
Set(value As String)
Session("theprevpage") = value
End Set
End Property
Private Function HandleSiteNode(ByVal sender As Object, ByVal e As SiteMapResolveEventArgs) As SiteMapNode
Dim currNode As SiteMapNode = SiteMap.CurrentNode.Clone(True)
Dim tempNode As SiteMapNode = currNode
Dim strPrev As String = PreviousPage
' Append parent pages query string back onto the parent's node URL
If Not tempNode.ParentNode Is Nothing Then
If strPrev.Contains("?") Then
tempNode.ParentNode.Url = tempNode.ParentNode.Url + "?" + strPrev.Split("?")(1)
End If
End If
Return currNode
End Function
And in the master page load function
If Not IsPostBack Then
AddHandler SiteMap.SiteMapResolve, AddressOf HandleSiteNode
PreviousPage = Request.UrlReferrer.ToString()
End If
Now, here is where it gets strange.
The first page is a login page the master load doesn't get called on. After I log in it then going to the main.aspx page, and it successfully saves the "login.aspx" page in the session state.
Now, when I go to navigate the 2nd time after logging in, the session state is set successfully, but by the time it gets into the HandleSiteNode which is called after the session was set successfully, the session still says the url is "login.aspx" and not "main.aspx"
No where else in the code am I setting this session state, it just seems to revert back to its previous value on its own.
No matter how many links I click & how many times the session is set, the Session variable will never change to anything else besides "login.aspx"
Help!
edit: Another odd detail, when I move the AddHandler line from master page into a non-master page, the session state is saved properly. However, if I try to move the Addhandler code into the Master page MainContent.Load function, it still doesn't work
SiteMapResolve is a static event.
This means that it doesn't have access to the session object. You'll note this if you put a breakpoint in your HandleSiteNode code and inspect the Session.SessionId property.
The examples on MSDN about the event all target the global.asax file which means that handler is really geared towards a single use of the site. Note that the MSDN example I linked to is a little jacked in that it attaches a new event on every page load, which will eat memory. The event should only be attached to once.
Click here for more info on potential ways to get around the issues.
Apparently, my web project has at least 2 different session states.
I can access the session state that contains the value I want by using
e.Context.Session("theprevpage")
This seems like a bit of a hack but it's working for me.

ASP.Net Session variables - struggling with the Cache

I'm using some session variables to store and pass data across several pages of an ASP.Net application. The behavior is a bit unpredictable though. I'm setting the session variable post page_load as follows
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If (Session.Item("ScholarshipID") = Nothing) Then
Session.Add("ScholarshipID", "Summer2011")
End If
Ok so far so good, on a normal page load. If the user completes the form action, hits the next page, and decides OH NO, i needed to change field xyz, and clicks back, corrects the data, then submits, the session variable is showing as NULL. Why would a cached session behave this way? I'm not destroying/clearing the variable, unless I fail to understand the scope of session variables.
try
If (IsNothing(Session("Scholarship"))) Then
Session("Scholarship") = "Summer2011"
End If

How to check if asp session is valid?

Im using outproc session that is managed by aspnet_state. Sometimes I get run time errors saying that the session is invalid. So I wanted to check if the session is valid for every request I make. But I couldn't find a proper way to do it like in this Question using Java.
Here is the code I'm using right now in the page_preinit event.It looks ugly but it works.
Try
Dim x = Session.Keys().Item(0)
Catch ex As Exception
Session.Clear()
End Try
Does any one knows a better approach?
Thanks
You could try checking the context object.
C#
if(Context.Session != null)
{
//Redirect to login page etc
}
VB (Used a C# to VB converter here..not sure if this is correct)
If Context.Session IsNot Nothing Then
    'Redirect to login page etc
End If
If you are using forms authentication and it is setup correctly, it should redirect for you. If you still need to be explicit, I would recommend placing this type of code in the Global.asax, or a base class that each of your pages could derive from, rather than adding it to every request.
Actually I solved the problem by checking the first element of the session( session.item(0) )
I put the code in try catch . if the there is an exception I just clear the session. This code is in a basepage for all my pages.
so in the preinit event my code look like this
Private Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Try
Dim x = Session.Keys().Item(0)
Catch ex As Exception
Session.Clear()
End Try
End Sub
It seems to be ugly but it does solve my problem.
Thanks everyone.
Just check the Session.Count instead of attempting to access the first item in an error handling block...

How do I detect if a request is a callback in the Global.asax?

I need to find a way to detect if a request is a callback when the Application_BeginRequest method is called.
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)<br />
Dim _isCallBack As Boolean = False
' Code to set _isCallBack is True or False Here
If Not _isCallBack Then
'... Some Code
End If
End Sub
I need to know what to replace "[Code to set _isCallBack is True or False Here]" with.
This may help you:
http://msdn.microsoft.com/en-us/magazine/cc163941.aspx
Search for the word __CALLBACKID:
To determine the callback mode, the ASP.NET runtime looks for a __CALLBACKID entry in the Request collection. If such an entry is found, the runtime concludes that a callback invocation is being made.
We needed to do this from within an app_code file where access to the Page.xxxx objects was not available. This is the code I ended up using:
If Not IsNothing(HttpContext.Current.Request("__CALLBACKID")) Then
'The request is a callback
Else
'The request is not a callback
End If
Maybe not the prettiest solution, but it does the job. We were using Array.IndexOf for a while, but it seems that sometimes that form parameter arrives back as lowercase parameter (not sure why or how), and Array.IndexOf is a case sensitive search.
Be careful looking for these kinds of __XXXX request keys. I remember reading somewhere that it's not a good idea to "shortcut" to these elements since their names could change in some future version of .net. Just keep that in mind!
I needed something similar and, following on Dean L's answer, figured .NET itself must know what to do. Looking in the HttpResponse.Redirect method with Reflector, you see code like this:
Page handler = Context.Handler as Page;
if (handler != null && handler.IsCallback)
{
//Code...
}
Seems to work fine in Global.asax.
Depends on the context of your question. I see you are talking about ASP.NET in the tags, using VB.NET. You can probably use:
If Not Request.IsPostback Then
' Your code here
End If

Resources