How to remove specific session in asp.net? - c#

I am facing a problem. I have created two sessions:
Session["userid"] = UserTbl.userid;
Session["userType"] = UserTbl.type;
I know how to remove sessions using Session.clear(). I want to remove the session "userType".
How do I remove a specific session?

Session.Remove("name of your session here");

There is nothing like session container , so you can set it as null
but rather you can set individual session element as null or ""
like Session["userid"] = null;

you can use Session.Remove() method; Session.Remove
Session.Remove("yourSessionName");

There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear() method. But the best way is to set another irrelevant object (usually null value) in the session in correspondance to a key. For example, to nullify Session["FirstName"], simply set it to Session["FirstName"] = null.

HttpContext.Current.Session.Remove("sessionname");
it works for me

A single way to remove sessions is setting it to null;
Session["your_session"] = null;

Related

How to read multiple cookie with same name in webapi using C#

We have two cookies created with same name.
When i am iterating through loop, i am always getting first cookie.
Is there way to access both cookie separately?
if (Request.Cookies.AllKeys.Where(x => x == "test").Count() > 1)
{
foreach (var cookie in Request.Cookies.AllKeys)
{
if (Request.Cookies[cookie].Name == "test")
{
var temp = System.Web.HttpContext.Current.Request.Cookies["test"];
temp.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(temp);
}
}
};
When a cookie already exists, and you update it (through the response's Cookies collection), either by adding or updating it, a second 'duplicate' cookie is added to the Request's Cookies collection. This duplicate one is actually the one you just updated.
Although I did not check this on MSDN documentation, I believe this is most probably by design. Why you ask? Because it allows you to get either YOUR current version of the cookie (the one you've just updated/added through the Response), or the one that was actually sent over by the user's browser (which is thus their current version of the cookie at this moment in time).
Now, using either Cookies.Get(name), Cookies[name] or -the way you are doing it- looping through the key collection (from the start) and then returning the first match, will always result in the first cookie beïng returned. This is the cookie as the user still knows it, thus not the one you've been updating during this request.
If you want to retrieve 'your' current version of the cookie, you must get the last one with that name, instead of the first. You can do so like this:
int index = Array.LastIndexOf(this.HttpRequest.Cookies.AllKeys, cookieKey);
if (index != -1)
{
result = this.HttpRequest.Cookies[index];
}
Of course this will also always return the correct cookie if you didn't update it within the current request.
we cannot have two cookies with the same name in a particular domain and also by default we get the cookies from the current domain. So I am not seeing a case where to you can get two cookies with the same name in the above-mentioned code.
Please mention your issue wit more detail.

Questions about Session variables

I am currently trying to allow users to "personalize" their background-image on a website I've created with C#-ASP.net. I imagined as far as that I create a if statement, checking if the currently logged in user matches with the session variable created when logging in, and if it does, it allows him to change his/her background-image. Before I did this, I also thought that the best way of testing if it would work that way is to try to write out the content of the session variable directly onto the page. Thats where the issue come in. All I am getting is the "name" of the session variable and nothing else. How can I get this changed?
The code below is pretty much what I've tried with the session variables this far
<%
// User with the name of "Bob" is logged in with code further up
var login_username = Request["login_username"];
Session["loggedIn"] = login_username;
Response.Write(Session["loggedIn"]);
// Results in it writing out "loggedIn".
// Expected "Bob".
%>
I'm going to be fair, I have no idea if this is enough for anyone to give me a hand and If I am even on the right track, but thats that. If theres a better way of doing this, I'm up for suggestions.
At the time of logging in, store your username into a session variable,
for eg: Session["loggedIn"] = username
Then, read the session value to a label text using
Convert.ToString(Session["loggedIn"]
Alternatively, one can write Response.Write(Session["loggedIn"]); to get the string of the variable.

Passing parameters to Controller ..but NOT on the URL

Is there a way to pass a parameter to a controller without putting it on the URL?
For example,
http://www.winepassionate.com/p/19/wine-chianti-docg-la-moto
has the value 19 on the URL. If you actually change that value to another, the page displays a different record even it the page name remains the same.
So I would like to NOT pass the ID on the URL but still be able to pass that to the Controller.
What's the recommended way to do so?
You can do a post and send it as a form parameter. I do not recommend this. Posts should be for requests that modify data. In this case you're most likely looking just to get that data. The fact that the id is in the URL is a good thing (see the Stack Overflow URLs for reference). If you really don't want the user to be able to modify it (I hope it's not because you think this makes it more secure, because it doesn't), you could do some simple encryption on it to make it more difficult to guess/produce a valid ID.
Using TempData, as some other suggest, is not a robust solution. It won't work for links on a page, just a GET after POST, and then only once since TempData is deleted after the next request.
Well, you have a couple of options:
Is this a form post? If so, then you can simply add a specific key value pair to your form when you submit it and then data will be passed along.
Is the URL unique to that resource? i.e. Does "Wine-chianti-docg-la-moto" exist as a unique representation of the number 19 in a database somewhere? If so, then you can simply do a lookup of that route component in your database to retrieve the value you need (or push that logic all the way down to the database).
Is that a value that is not expected to change a bunch? You can set that value in Session or in a cookie that would be persisted across pages and then pull it from the respective collection.
Are you redirecting to this page from another request on your server? If so, then you can use TempData to store this temporary value. However, I would recommend against this approach, as it is very transient and not good practice imo.
Lastly, you can obscure the value on the URL if you dont want it to be easily user editable. Encrypt it with some algorithm, and then decrypt it on the destination page. The user will be unlikely to be able to alter the ID by typing in a different value in the URL.
If the page is a GET, and you are following the PRG like you should be (Post-Redirect-Get) then you can use TempData["dataName"] = value; in your [HttpPost] controller and then consume it in your [HttpGet] method. It really depends on how the page is being called.
However, there is nothing wrong in letting the user change that number if it is not security related, and is common practice to show non-vital information in the url like that.
You should use TempData in this case. A good read on this can be found on this blog.
TempData allows you to store a value temporarily between requests and is, by default, erased after being accessed.
// TempData samplepublic ActionResult Featured(){ var featuredProduct = new Product { Name = "Assorted Cupcakes", Description = "Delectable vanilla and chocolate cupcakes", CreationDate = DateTime.Today, ExpirationDate = DateTime.Today.AddDays(7), ImageName = "cupcakes.jpg", Price = 5.99M, QtyOnHand = 12 };

Page Reload - Keeping Variables

How do I go about when page is reloaded that I make sure the variables I have declared at the top o my class do not get reset. IE I have a counter that is originally set at 0 if I use a postback control it resets that variable how do i go about not having this happen in C#?
Are you looking for a value specific to the client or to the server?
If you want something specific to the client use a cookie or session value.
If you are looking something specific to the server use a static class, application or cache value.
Use ASP.Net Session or Cookies. Or you can store their values in hidden fields. You can read about theese and outher option in following article.
Put the value you want to save in a cookie.
if you´re using a postback, not a link, you should save your data into viewstate.
vb
Public Property MyValue() As String
Get
Dim _mv As Object = ViewState("MyValue")
If Not _mv Is Nothing Then
Return _mv.ToString
End If
Return String.Empty
End Get
Set(ByVal value As String)
ViewState("MyValue") = value
End Set
End Property
C#
public string MyValue {
get {
object _mv = ViewState("MyValue");
if ((_mv != null)) {
return _mv.ToString();
}
return string.Empty;
}
set { ViewState("MyValue") = value; }
}
ViewState is saved along PostBacks, if you stay on the current page. For Example if you are on page.aspx and using a <asp:button> that is clicked each time, you can use Viewstate as a place for saving some of your data, it looks in the page source code like this
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4Mzg3MjEyMzdkZNNlI9zvMeIGeUB4MZbJA2gmsHns9IsmAy/c4dQMybXD" />
the viewstate is generated automatically
That data is not persisted on HTTP Requests; you need to persist it in a cookie, hidden control, or manually store it in view state.
If you're manually doing a page counter, consider storing it in session state.

Accesing Server Control from other webform

I have 2 webforms with 1 ListBox Control on each of them.
How do I access the Listbox that's located on webformA from webformB?
For example I wish to declare something like this string name = ListBoxWebformA.SelectedValue.ToString(); on WebFormB, so that I can work with that value in the code of WebFormB.
The ListBox on WebFormA lists several names.
When I select a name from the listbox and press the OK button I call Response.Redirect("~/WebFormB.aspx");
So from WebFormB I wish to access this "name" by putting the selected value into a string.
Based on your edit, the easiest (possibly best) way to go about doing this will not be to try to maintain a stateful instance of webformA during the request to webformB. Once the user is redirected, assume that webformA is gone.
Instead, when you're about to perform the Response.Redirect() to webformB, include in some way the value from webformA that you wish to pass along. The easiest way to do this will be on the query string. Something like:
Response.Redirect(string.Format("~/WebFormB.aspx?name={0}", HttpUtility.UrlEncode(ListBoxWebformA.SelectedValue.ToString())));
Then, in webformB you can access the value:
string name = Request.QueryString["name"];
Note that you'll want to do some error checking, etc. Make sure the value is actually selected before appending it to the redirect URL on webformA, make sure Request.QueryString["name"] contains a value before using it in webformB, etc.
But the idea in general is to pass that value along, by query string or POST value or Session value or some other more stateful means, when redirecting from one form to the other.
I guess you have to resort to either passing the value from A to B in the query string or storing the value in Session and reading afterwards.
So would be a
Response.Redirect(string.Format("~/WebFormB.aspx?YourVariable={0}",HttpUtility.UrlEncode(ListBoxWebformA.SelectedValue));
and you can read it in Form B like
Request.QueryString["YourVariable"]
If the values are not sensitive this approach above would be the best.
If they are... To store in Session:
Session["YourVariable"] = ListBoxWebformA.SelectedValue
And to read...
if (Session["YourVariable"] != null) {
var listAValue = Session["YourVariable"].ToString()
}

Categories