ASP.NET Session DataSet, DataTable, and .NET Class Storage (2023)

ASP.NET Session stores values, DataSets, and classes.

Basic use of Session in ASP.NET (C#):

STORE:
DataSet ds = GetDataSet(whatever parameters);
Session["mydataset")=ds;

RETRIEVE:
DataSet ds = (DataSet)Session["mydataset"];

Storage location

InProc - session kept as live objects in web server (aspnet_wp.exe). Use "cookieless" configuration in web.config to "munge" the sessionId onto the URL (solves cookie/domain/path RFC problems too!)

StateServer - session serialized and stored in memory in a separate process (aspnet_state.exe). State Server can run on another machine

SQLServer
- session serialized and stored in SQL server

Performance

InProc - Fastest, but the more session data, the more memory is consumed on the web server, and that can affect performance.

StateServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 15% slower than InProc. However, the cost of serialization/deserialization can affect performance if you're storing lots of objects. You have to do performance testing for your own scenario.

(Video) How to Store Datatable In Session and retrieve from Session?

SQLServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 25% slower than InProc. Same warning about serialization as in StateServer.

Performance tips for Out-of-Proc (OOP) modes

If you're using OOP modes (State Server or SQL Server), one of your major cost is the serialization/deserialization of objects in your ASP.NET session state. ASP.NET performs the serialization/deserialization of certain "basic" types using an optimized internal method. "Basic" types include numeric types of all sizes (e.g. Int, Byte, Decimal, ... etc), String, DateTime, TimeSpan, Guid, IntPtr and UIntPtr.

If you have an ASP.NET session variable (e.g. an ArrayList object) that is not one of the "basic" types, ASP.NET will serialize/deserialize it using the BinaryFormatter, which is relatively slower.

For performance sake it is better to store all ASP.NET session state data using one of the "basic" types listed above. For example, if you want to store two things, Name and Address, in session state, you can either:

(a) store them using two String session variables, or
(b) create a class with two String members, and store that class object in a session variable. Performance wise, you should go with option (a).

Robustness

InProc - Session state will be lost if the worker process (aspnet_wp.exe) recycles, or if the appdomain restarts. It's because ASP.NET session state is stored in the memory space of an appdomain. For details, see KB324772.

StateServer - Solve the session state loss problem in InProc mode. Allows a webfarm to store ASP.NET session on a central server. Single point of failure at the State Server.

SQLServer - Similar to StateServer. Moreover, session state data can survive a SQL server restart, and you can also take advantage of SQL server failover cluster, after you've followed instructions in KB 311029.

Caveats

(Video) ADO.NET - Understanding DataSet

InProc

- It won't work in web garden mode, because in that mode multiple aspnet_wp.exe will be running on the same machine. Switch to StateServer or SQLServer when using web garden. Also Session_End event is supported only in InProc mode.

StateServer

- In a web farm, make sure you have the same <machineKey> in all your web servers. See KB 313091 on how to do it.
- Also, make sure your objects are serializable. See KB 312112 for details.
- For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm. See KB 325056 for details

SQLServer

- If you specify integrated security in the connection string (e.g. "trusted_connection=true", or "integrated security=sspi"), it won't work if you also turn on impersonation in asp.net. Unfortunately, this bug isn't reported in KB yet. (There is a QFE fix for it.)

- Also, make sure your objects are serializable. See KB 312112 for details.

- For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm. See KB 325056 for details.

FAQ's:

Q: ASP.NET Session states works on some web servers but not on others.
A: Maybe machine name problem. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112 .

Q: Why isn't Session_End fired when I call <i>Session_Abandon</i>?
A: First of all, Session_End event is supported only in InProc mode. In order for Session_End to be fired, your session state has to exist first. That means you have to store some data in the session state and has completed at least one request.

(Video) (#15) How to use Session in ASP MVC .NET 6.0 ? | Store User Data in Session

Q: Why are my ASP.NET Session variables lost frequently when using InProc mode?
A: Probably because of application recycle. See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316148

Q: Why does the SessionID remain the same after the Session times out or abandoned?
A:Even though the session state expires after the indicated timeout period, the session ID lasts as long as the browser session. What this implies is that the same session ID can represent multiple sessions over time where the instance of the browser remain the same.

Q: Why does the SessionID changes in every request?
A: This may happen if your application has never stored anything in the session state. In this case, a new session state (with a new ID) is created in every request, but is never saved because it contains nothing.

However, there are two exceptions to this same ASP.NET session ID behavior:

- If the user has used the same browser instance to request another page that uses the session state, you will get the same session ID every time. For details, see "Why does the SessionID remain the same after the Session times out?"
- If the Session_OnStart event is used, ASP.NET will save the session state even when it is empty.

Q: Can I share session state between ASP.NET and ASP pages?
A: Yes! Here is our article on how to do this in either direction using two "intermediate" pages. And here is an article on how to do it with SQL Server.http://www.eggheadcafe.com/articles/20021207.asp

Q: What kinds of object can I store in session state?
A: It depends on which mode you are using:
- If you are using InProc mode, objects stored in session state are actually live objects, and so you can store whatever object you have created such as <b>custom classes</b>, <b>DataSet</b>, or a <b>DataTable</b>.
- If you are using State Server or SQL Server mode, objects in the session state will be serialized and deserialized when a request is processed. So make sure your objects are serializable and their classes must be marked as so. If not, the session state will not be saved successfully. In v1, there is a bug which makes the problem happen unnoticed. See this KB for more info:
http://support.microsoft.com/directory/article.asp?ID=KB;EN-US;q312112

Q: How come Response.Redirect and Server.Transfer is not working in Session_End?
A: Session_End is fired internally by the server, based on an internal timer. Thus, there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transferdoes not make sense and will not work.

Q: Do I have a valid HttpContext in Session_End?
A: No, because this event is not associated with any request.

Q: Will my session state be saved when my page hit an error?
A: No. Unless you call Server.ClearError in your exception handler.

Q: How do I use session state with web services?
A: The extra trick needed is on the caller side. You have to save and store the cookies used by the web service. See the MSDN documentation on HttpWebClientProtocol.CookieContainer property. However, please note if you're using proxy object to call a web service from your page, the web service and your page cannot share the same session state due to architecture limitation.This can be done if you call your web service through redirect.

(Video) DataAdapter, DataTable, DataSet In Ado.Net- Part 1 | with practical example

Q: I am writing my own HttpHandler. Why is session state not working?
A: Your HttpHandler has to implement the "marker" interface IRequiresSessionState or IReadOnlySessionState in order to use session state.

Q: I am using a webfarm, and I lost session state when directed to some web servers.
A: For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm. See KB 325056 for details.

Q: Why isn't session state availabe in the Application_OnAcquireRequestState (or other) event handler?
A: Session state is available only after the HttpApplication.AcquireRequestState event is called. For details, see: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconhandlingpublicevents.asp

Q: If using "cookieless", how can I redirect from a HTTP page to an HTTPS page?
A: Try this:
String originalUrl = "/fxtest3/sub/foo2.aspx";
String modifiedUrl = "https://localhost" + Response.ApplyAppPathModifier(originalUrl);
Response.Redirect(modifiedUrl);

NOTE: Fully qualified URLs in the response.redirect, server.transfer, and FORM action
tags cannot be used with cookiless sessions. Here is an example of a fully qualified

URL: http://www.eggheadcafe.com/default.asp More info here:

Q: What isn't Session available in my event handler in global.asax?
A: It depends on which event you're handling. Session is available only after AcquireRequestState event.

Q: Does session state have a locking mechanism that serialize the access to state?
Session state implements a reader/writer locking mechanism:
- A page (or frame) that has session state write access (e.g. <%@ Page EnableSessionState="True" %>) will hold a writer lock on the session until the request finishes.
- A page (or frame) that has session state read access (e.g. <%@ Page EnableSessionState="ReadOnly" %>) will hold a reader lock on the session until the request finishes.
- Reader lock will block a writer lock; Reader lock will NOT block reader lock; Writer lock will block all reader and writer lock.
- That's why if two frames both have session state write access, one frame has to wait for the other to finish first.

By Peter Bromberg Popularity(66323 Views)

FAQs

How much data can session store? ›

Session storage can also accommodate a huge amount of data. Most browsers, including Chrome and Firefox, can store about 10 MBs of data in session storage.

What is the maximum size of ASP.NET session? ›

Session size is about 10-20KB max.

How do you store dataset in session? ›

Syntax
  1. Save Data to Session Storage. sessionStorage.setItem("key", "value");
  2. Read Data from Session Storage. let lastname = sessionStorage.getItem("key");
  3. Remove Data from Session Storage. sessionStorage.removeItem("key");
  4. Remove All (Clear session Storage) sessionStorage.clear();

How to store DataTable in session in ASP.NET Core? ›

Solution 4
  1. Adding DataTable into Session Veriable:
  2. Set into Session variable as. Session["MyDataTableSessionName"]= "MyDataTable" i.e. DataTable myDataTable=new DataTable(); Session["MyDataTable"]= myDataTable;
  3. Retrive that DataTable from Session: DataTable myDataTable =(DataTable)Session["MyDataTable"];
Jun 8, 2012

Is it good to use session storage? ›

Session storage allows you to store data in the browser depending on the system memory and the data stored in the browser until the browser is closed. In other words, closing the browser will clear all the data stored in session storage.

Is it safe to store data in session storage? ›

We've already discussed origin sandbox: Local Storage, Session Storage, cookies. Our verdict was that this is not a secure option, with the exception of HttpOnly cookies.

How big can a session variable be? ›

As @Thariama said, there's no limit on the number of variables; also, there's no limit on the amount of data you can store in a session (I've seen sessions tens of MB in size).

How can increase session time in ASP.NET application? ›

Open up IIS. Select your website from the list of sites. Click on Session state on the right. Now enter your session timeout under the cookie settings.

Is ASP.NET full stack? ›

. NET is a full-stack development platform that enables you to build, deploy, and manage applications and services. It provides a comprehensive and flexible technology stack for developing modern web applications and services. ASP.NET Core is a new open-source and cross-platform version of .

Should I use session storage or local storage? ›

For most cases, we use the local Storage object if we want some data to be on the browser. If we want it on the server, then we use it, and the session storage is used when we want to destroy the data whenever that specific tab gets closed or the season is closed by the user.

What should not be stored in session? ›

Things like Database Data such as User Rows should not be stored in the session and you should create a separate cache mechanism to do this for you.
...
3 Answers
  • strings.
  • boolean's.
  • integer's.
  • objects.
  • arrays.
  • resources.
Jan 11, 2011

Where should I store session data? ›

There are a few options:
  1. Store them on the filesystem in plaintext. ...
  2. Encrypt session IDs and data using the database's inbuilt encryption routines. ...
  3. Encrypt your session IDs and session data in the database, using a key set in a config file on the server somewhere.
Jan 9, 2017

How to store data in session storage in C#? ›

C# Code
  1. using System;
  2. After that write the following code in button click.
  3. protected void Page_Load(object sender, EventArgs e) {}
  4. // Set Session values during button click.
  5. protected void btnSubmit_Click(object sender, EventArgs e) {
  6. Session["FirstName"] = txtfName.Text;
  7. Session["LastName"] = txtlName.Text;
Jul 24, 2019

Where is session data stored in .NET Core? ›

A session state keeps the data as long as the cookie is configured to last. The default session state version in ASP.NET Core stores the session data in the memory (RAM) of the web server.

How to get session storage value in C#? ›

Get session storage
  1. var ProductName = sessionStorage.getItem('ProductName');
  2. //OR.
  3. var ProductName = sessionStorage.ProductName;
Apr 1, 2017

Can session storage be hacked? ›

After a user starts a session such as logging into a banking website, an attacker can hijack it. In order to hijack a session, the attacker needs to have substantial knowledge of the user's cookie session. Although any session can be hacked, it is more common in browser sessions on web applications.

How do I clean session storage? ›

We can get specified session storage using the getItem() method. We can clear the session storage by using the clear() method.

Does session storage survive refresh? ›

Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser. What's interesting about them is that the data survives a page refresh (for sessionStorage ) and even a full browser restart (for localStorage ).

What is the safest form of data storage? ›

For the best security for your files, you need a cloud storage service that offers zero-knowledge encryption. This means that your provider does not store a copy of your encryption key. Without the key, the company cannot access your files — period.

What is the safest data storage? ›

Top 10 Safest Cloud Storage
  • Microsoft OneDrive.
  • Google Drive.
  • Egnyte Connect.
  • MEGA.
  • Tresorit.
  • SpiderOak.
  • Koofr.
  • Conclusion.
Mar 3, 2021

What is the safest place to store data? ›

Cloud providers often offer premium-grade encryption out of the box. And even better: tech behemoths like Microsoft, Amazon and Google can provide you with AES 256 encryption, which makes it near to impossible for attackers to read any data they might steal.

How much memory does a variable take? ›

The variable "a=b" contains 1 char 'a' for the name, and 1 char 'b' for the value. Together 2 bytes.

Can you store an array in a session variable? ›

Yes, PHP supports arrays as session variables.

How many pieces of data does a variable hold? ›

A variable can hold one value (piece of data) at a time. This value can change throughout the execution of a program. When a new value is placed in (or assigned to) a variable, it replaces the last value. Each variable used in a program is given a unique identifier (name).

How can I improve my session time? ›

10 Ways to Improve Average Session Duration
  1. Include Videos.
  2. Break Up Text With Engaging Images.
  3. Understand the Customer Journey.
  4. Track Visitor Behavior through Your Pages.
  5. Create a Smooth User Experience.
  6. Format Your Content Properly.
  7. Focus on Interlinking.
  8. Build Content Libraries.
Sep 15, 2022

How do I increase the number of sessions per user? ›

How To Increase Your Website's Engaged Sessions per User
  1. Moving a lead down the sales funnel.
  2. Encourage a repeat purchase.
  3. Building a relationship with customers.
  4. Increasing search ranking due to SEO benefits.
Jul 21, 2022

What is the salary of full stack .NET developer? ›

Dot Net Fullstack Developer salary in India ranges between ₹ 2.4 Lakhs to ₹ 19.3 Lakhs with an average annual salary of ₹ 7.1 Lakhs.

What is the salary of full stack NET developer? ›

full stack . net developer salary in India ranges between ₹ 2.0 Lakhs to ₹ 18.7 Lakhs with an average annual salary of ₹ 6.2 Lakhs. Salary estimates are based on 370 latest salaries received from full stack . net developers.

Which full stack developer has highest salary? ›

Highest salary that a Full Stack Developer can earn is ₹16.1 Lakhs per year (₹1.3L per month).
...
These are the top skills of a Full Stack Developer based on 29466 jobs posted by employers.
  • Javascript.
  • HTML.
  • Java.
  • Angular.
  • JQuery.

How do I know if session storage is empty? ›

write(sessionStorage. getItem('value1')); most browser will render it as null if its empty. However, it's a different story for text inputs. IE will include the word null as value in the text box.

Where should you store the session data in asp net? ›

The default behavior is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source.

Can I save an object in sessionStorage? ›

There are a couple of ways to save arrays and objects to browser storage. The Web Storage API allows us to store items in a more intuitive way using two mechanisms: localStorage and sessionStorage . For both of these mechanisms: Items are converted to a JSON string using JSON.

What kind of data is stored in session? ›

A session stores the variables and their values within a file in a temporary directory on the server. Cookies are stored on the user's computer as a text file. The session ends when the user logout from the application or closes his web browser. Cookies end on the lifetime set by the user.

Is session data stored on server? ›

Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as the server.

What is the difference between local storage and session storage in C#? ›

The difference between sessionStorage and localStorage is that localStorage data does not expire, whereas sessionStorage data is cleared when the page session ends. A unique page session gets created once a document is loaded in a browser tab. Page sessions are valid for only one tab at a time.

How large can a session variable be? ›

As @Thariama said, there's no limit on the number of variables; also, there's no limit on the amount of data you can store in a session (I've seen sessions tens of MB in size).

What is the maximum size of flask session? ›

Session data is limited by the size of the cookie (usually 4 KB) Sessions cannot be immediately revoked by the Flask app.

What is the disadvantage of session storage? ›

Cons
  • Its data is plain text; hence it is not secure by design.
  • The data type is limited to string; hence it needs to be serialized.
  • Data can only be read on the client-side, not on the server-side.
Nov 1, 2022

What can store up to 25 GB of data? ›

Answer: A Blu-ray disc, for example, can store 25 GB (gigabytes) of data on a single-layer disc and 50 GB on a dual-layer disc. In comparison, a standard CD is the same physical size, but only holds 700 MB (megabytes) of digital data.

Is there a limit to number of variables? ›

There is no known limit on count of variables, also because any variable can have different size, but there is a memory limit on execution stack size.

How long do session variables last ASP Net? ›

A session automatically ends if a user has not requested or refreshed a page in an application for a specified period of time. This value is 20 minutes by default. You can change the default for an application by setting the Session.

Videos

1. DataSet in asp.net Part 11
(kudvenkat)
2. How to store a list in session variable in aspx
(piyush kumar)
3. Using Sessions in ASP .NET C#
(Manthan Dave)
4. Part 3 (c# sql database tutorial) - DataSet, DataTable and SqlDataAdapter
(Maximum Code)
5. Inserting 10 Million Records in SQL Server with C# and ADO.NET (Efficient way)
(gavilanch3)
6. DataTable in C# Net
(T V Rao)
Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated: 01/29/2023

Views: 6366

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.