How to Kill A Session or Session ID (ASP.NET/C#) - c#

How can I destroy a session (Session["Name"]) when the user clicks the logout button?
I'm looking through the ASP.NET API Reference on MSDN and it doesn't seem to have much information. It seems rather limited. But I cannot find any other pages for ASP.NET Classes etc.
I have tried:
Session.Abandon(); and
Session.Contents.Remove("Name"); neither of them work. ( I found these in a forum from a Google search)

The Abandon method should work (MSDN):
Session.Abandon();
If you want to remove a specific item from the session use (MSDN):
Session.Remove("YourItem");
EDIT: If you just want to clear a value you can do:
Session["YourItem"] = null;
If you want to clear all keys do:
Session.Clear();
If none of these are working for you then something fishy is going on. I would check to see where you are assigning the value and verify that it is not getting reassigned after you clear the value.
Simple check do:
Session["YourKey"] = "Test"; // creates the key
Session.Remove("YourKey"); // removes the key
bool gone = (Session["YourKey"] == null); // tests that the remove worked

It is also a good idea to instruct the client browser to clear session id cookie value.
Session.Clear();
Session.Abandon();
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-10);

Session.Abandon()
This marks the session as Abandoned, but the session won't actually be Abandoned at that moment, the request has to complete first.

From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP.
(I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.

Session.Abandon() this will destroy the data.
Note, this won't necessarily truly remove the session token from a user, and that same session token at a later point might get picked up and created as a new session with the same id because it's deemed to be fair game to be used.

You kill a session like this:
Session.Abandon()
If, however, you just want to empty the session, use:
Session.Clear()

Session.Abandon()
is what you should use. the thing is behind the scenes asp.net will destroy the session but immediately give the user a brand new session on the next page request. So if you're checking to see if the session is gone right after calling abandon it will look like it didn't work.

Session["YourItem"] = "";
Works great in .net razor web pages.

Session.Abandon(); did not work for me either.
The way I had to write it to get it to work was like this. Might work for you too.
HttpContext.Current.Session.Abandon();

Related

Disable Cookieless Session .Net MVC 5

We previously had cookieless session enabled on our application. We have disabled this and gone to session cookies however we are having a problem. Users who had the session ID in their URL as a bookmark are still able to navigate to the site with the session id in the url. I have set it to not regenerate expired sessions but it is still allowing it anyways. It also ends up creating a session cookie in addition and then we are getting random session loss. I've come up with a few wonky workarounds like stripping it out using a URL rewrite and stripping it out via javascript but this seems bad. Is there anything built in that I am missing that can help with this? Not that it should matter for this but I will add we are using state server.
For anyone else looking for a solution that won't require users to update their bookmarks I was able to use the following in my Global.asax Application_BeginRequest:
void Application_BeginRequest(object sender, EventArgs e) {
if (CookielessValuesExist()) {
Response.Redirect(Request.Url.OriginalString, true);
}
}
private bool CookielessValuesExist() {
string cookieless = Request.Params["HTTP_ASPFILTERSESSIONID"];
if (string.IsNullOrWhiteSpace(cookieless)) {
return false;
}
return true;
}
A URL rewrite is a good solution to this.
However if you would like users to update their bookmarks, (so you can eventually retire the URL rewrite) you might consider having your URL rewrite send them to a page telling them so:
Oops! That link doesn't work.
And then giving them the usual options to log in etc.

Implement logout on every page

I want to implement logout option on every view of my webpage.For this i assigned null to my session variable. And also remove the data in cache. But I studied that to remove the data from cache put some extra burden on web server because no data is stored in cache...
So, what can be alternative to this problem.
Create a _Layout page and keep your Login/Register/Logout there. You can check by creating a default Web MVC application and see how login/register/logout rendering in every page.
There are many ways to clean cache by using java script.
I like this way,
<script>
function ClearHistory()
{
var backlen = history.length;
history.go(-backlen);
window.location.href = loggedOutPageUrl //Pass your Index Page
}
</script>
Or else the easiest way is just clear the cache in LogOff() method, just like bellow,
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Login");
}
Please check this Link There are many way to clear cache, so that back button will not work after logout.

asp.net not saving my cookies

I know it's probably something simple, but I just can't figure it out. Note that I'm doing this on my own PC, not through a server (localhost) and I've considered that might be the issue, but I see nothing online about it being the case so maybe it's just a thought.
So I am trying to simply get a string and store it into a cookie and then read it later. Here's the lines of code that "saves" the cookie and its information:
HttpCookie cookie = new HttpCookie("userName", someInfo);
Response.Cookies.Add(cookie);
lblProof.Text = "Value: " + Request.Cookies["userName"].Value;
If I try this method, it fails. No information is shown on the lblProof. At first, I thought maybe someInfo didn't have anything in it (note it's a string). However, when I set the lblProof.Text to someInfo, it DOES show it. I've tried simply doing
Response.Cookies["userName"].Value = someInfo;
But that didn't work either. So what's causing this thing to not work at all? And yes, I've tried HttpContext.Current.Response and Request.

My Session variable is always null

I'm creating a movie ticket reservation project. I want to get username from page1 and display it on page2 (using session variable)
Page1:
string uname = TextBox1.Text;
Session["UName"] = uname;
Session.Timeout = 30;
Page2:
if ((string)Session["UName"] != null)
{
string user = (string)Session["UName"];
}
and I placed a sign out button in page2 to remove session variable value. But the session variable is always null.
I've already used cookies in the page1 and will this be a cause? or what else? Please Help. Thanks in advance.
This usually occurs when doing a Response.Redirect after setting the session variable. You can work around this issue by calling the overload instead:
Response.Redirect("...", false); // false = don't stop execution
//causes ASP.NET to bypass all events and filtering in the HTTP pipeline
//chain of execution and directly execute the EndRequest event
HttpContext.Current.ApplicationInstance.CompleteRequest();
The underlying issue is a ThreadAbortException which is often ignored because it doesn't break the application. This is a known issue, and you can learn more about it here: http://support.microsoft.com/kb/312629.
Side Note
On a side note, you shouldn't be resetting your Session.Timeout value in the code like that. I can't be sure, but that may also have an adverse affect on your logic. Instead, you should specify the session timeout in the web.config under the system.web section:
<sessionState timeout="60" />
See this answer on when the Session can be null:
What should I do if the current ASP.NET session is null?
I personally often ran into this issue when I was using async requests with completion callback. In these callbacks I wanted to set something in the session and it was null.
I also had same problem,
I was toggling between debugging two different sites on localhost and there were two cookies for the session ID.
I deleted the cookies via Chrome's developer tools [Press F12 in Browser]->Application->Storage->Cookies

ASP.NET sessionID will not update

I click on refresh button which should restart session:
protected void btnRefresh_Click(object sender, EventArgs e)
{
HttpContext.Current.Session.Abandon();
HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
mycookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(mycookie);
LblSessionID.Text = HttpContext.Current.Session.SessionID+
" test btnRefresh_Click";
LblIsNewSession.Text = Session.IsNewSession.ToString();
}
But when the button is clicked, the SessionID value in LblSessionID still displays the old value but another label LblIsNewSession will show it as true for IsNewSession. The LblSessionID will then reflect the actual SessionID value when I use asp.net control (like dropdown) that has autopostback="true" and from there SessionID sticks around.
I do use global.asax
Any idea why LblSessionID isn't behaving as it should and is waiting for next postback to start reflecting actual value?
When I launch the web application, the problem is the same - LblSessionID show different value and then change after first postback and stays the same from there.
That's the way it works - If you Abandon the session it won't reflect that until the next Request. It makes sense if you think about it...
Say you have a user that accesses your site and gets a Session ID of 123 (not reflective of an actual value, I know). When you click your button to get a new Session ID, the user's request is from the old Session, and that is the value that is reflected during that Request. Once the session is reset (or abandoned or whatever), the user gets a new Session ID of 321 and subsequent Request's will then reflect that new session ID.
SessionId is not reliable unless you actually store something (anything) in the session.
try
Session.RemoveAll();
Session.Clear();
It is not your code, it is a documented behavior:
"The Abandon method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is examined at the end of the page request. Therefore, the user can still use session objects after you call the Abandon method. As soon as the page processing is completed, the session is removed."
(source: http://support.microsoft.com/kb/899918)
The Abandon() method flags the session collection for clearing at the end of the request, it does not actually clear it immediately.
You can either call the RemoveAll() or Clear() methods for instant deletion of the objects, or issue a Response.Redirect call to the page itself and re-test for the existence of the data.

Categories