Can any one help me in explaining the detailed and proper use of ASP.NET Sessions.
i read many web portals and blogs but i do not understand how to and where to use the sessions.
we create many sessions on page, for login, transfering some values from one page to another. but what is its impact on multiple users like more than 10000 users accessing the website, server transfer rate. memory storage, etc.
This may help many beginners, and also experienced person to properly use sessions in their project.
Any help is appreciated.
This is roughly how it works:
When the user visits your webpage, a session ID is set in a cookie in the user's browser. Each time the browser sends a request to the server, the browser will pass the cookie containing the session ID to the server. This allows the server to recognize the user and associate data with the user across multiple page requests (you can use sessions without cookies if you want to).
The server will by default store this data in memory. However, if multiple webservers are running the application and serving the same user, they will all need to know about the user's session data. Thus, you can configure your application to store session data using the "ASP.NET State Server" Windows service, or you can store the data in a SQL database (or you can write your own Session State Provider and store the data wherever you like). Moreover, storing the session data in memory is obviously a bad choice if you are worried your machine might crash (that obviously should worry you).
As for the "proper and detailed" use of ASP.NET sessions it is hard to say - it depends on what you are trying to achieve.
If you can help it, you should store only small amounts of data in sessions, as the combined sessions of all users visiting your website may take up quite a lot of space. Moreover, if you are using the ASP.NET State Server or the SQL Server session state stores the data you store needs to be serialized and deserialized, which will take a non-trivial amount of time for data of non-trivial size.
If what you are planning to store isn't confidential, an alternative approach might be to store the data in a cookie. That way your server will not have to worry about storing the data at all. This way you are trading memory (or disk space or whatever storage mechanism you choose) for bandwidth, as the cookie will now be part of the payload for every request.
Related
I have an order system developed on asp.net 4 web forms. I need to store order details (order object) for a user on the cache in order to manage it till I save it in the DB.
I want to install my site at least on two server with option to scale for more in the future .
As you know , the two servers are located behind load balancer , so I need the cached order object to be shared on the both servers.
I hear about App fabric.
Any recommendation to good frameworks to do that , Hope will be simple and easy to maintain one .
Thanks in advance ...
I need to store order details (order object) for a user on the cache
in order to manage it till I save it in the DB.
If your data is not persisted, SQL Server-based Session state will work across machines on a per-user basis and can be configured with a minimum of fuss.
However, I would suggest regularly saving the order to your application database (not just the Session database) so that the user doesn't lose it. This is fairly standard practice on e-commerce sites. Unless the order process is very short, inevitably the user will want to pause and return, or accidentally close the browser, spill coffee into their computer, etc.
Either way, the database makes a good intermediate and/or permanent location for this data.
Do ASP.NET Session[string key] data need to be encrypted to be secure?
If such data always stays on the server, doesn't that make it safe to store credit card information, passwords, etc. there, as long as the data were sent via SSL from the client?
With all the downvotes being thrown around here, I'll add my own two cents:
I think that anything that stays in server memory, including ASP.NET Session data, is safe in unencrypted form. An attacker would have to be able to execute code on the server in order to read the memory.
On a side note, once it's stored in a database, data should be encrypted. If it's sent to the client, it should also be encrypted, but that's outside the scope of this question. Lastly, of course, the data must be encrypted on its way from the client to the server.
Anything sensitive should go straight to the database, and not hang around in memory longer than needed. I don't understand why you'd need to store passwords or credit card data in session variables anyway, are you passing them between pages?
No. You should never store this information in the session. Even encrypted this information is vulnerable. Sessions may get hijacked, a server may get compromised and then everything that is in memory that happens to be used in memory as plaintext will be viewable to anyone with a hex editor. If you need references to this information, you should create hashes that are stored and not replayable that reference the information in a secure datastore.
EDIT: For those that think session data is safe:
http://en.wikipedia.org/wiki/Session_hijacking
http://en.wikipedia.org/wiki/Session_fixation
http://en.wikipedia.org/wiki/Session_poisoning
http://www.owasp.org/index.php/2.0_Session_State_(in)security_(and_the_dangers_of_State_Server)
There are ways of protecting session data, but if you need to keep very sensitive information such as passwords or credit card numbers, the session is not the place for it. Try coding to the Sarbanes Oxley legal requirements for banking and medical applications, and you'll find in your first audit that this is one of the first things that gets checked.
http://en.wikipedia.org/wiki/Session_management
I share m.edmondson idea, in the fact that sensitive information should be stored in database, (there are many techniques to dealing with sql-injection). Also for securing your site you should use HTTPS. But if you're going to store information that is not so sensitive for passing between pages you can use session variables, don forget to delete such variables as soon as possible. Remember you can aver going to the database to retrieve the data, only non-sensitive and time-consuming data should be stored in session scope.
Depends -- how much do you trust every other app on your server?
The question refers to the data being stored in memory on the same server, but that's just the default configuration. You can also set up a state server, write to a nosql db etc.
Stateless web servers are becoming increasingly more common thanks to the rise of the cloud and platforms-as-a-service.
Depending on your security policy, credit cards and passwords may not be the only information that you consider "confidential". Some orgs consider customer information such as addresses to be confidential as well. This means that any multi-step session checkout would contain "confidential" information.
The answer to this specific question may be a "no", but future readers might need to consider these additional items as well.
I am having 2 applications Suppose A and B. I am having a webpage in Application A where i am Setting the Session and in Application B i want to retrieve that session.How can i do that with out using DB?
Sessions are application specific and I don't believe you can share data between two applications via the session. You will need to pass the data through some other medium. You could serialize it and pass it via a POST parameter. You may also be able to use a cookie. If it is really small data, you could just pass it in the GET parameters of the query string.
I agree with NYSystemsAnalyst - and here's a FAQ on how to transfer session from a classic ASP app to ASP.NET. The code can nearly be copied to do the same thing in this case.
http://www.tek-tips.com/faqs.cfm?fid=2943
When you say without using a Database I guess you mean without using a third party database. There is no way around the fact you need to store and retrieve data while protecting against simultaneous access of underlying data structures causing problems, and this pretty much makes it a database. You could implement something simple by allocating some shared memory and using semaphores to protect access to it. Also you could have app A inform app B of changes to session state and have app B track these. This communication could be done over a named pipe between the apps. What OS are you targeting?
How are you Identifying you user between the applications?
What do you need in the session?
Not sure, but a web-service or wcf that passes the session variables back and forth for a given username || id?
( maybe not the session exactly but a object you could used to build/populate the session on both applications... )
User start session in App A, just before they move to App B store a small version of the session variables needed in cache with high priority but short expiry( this is what the web service would look for).
User stars session in App B, App B calls web service to see if user was in App A... if so get variables needed for App B?
No DBs, but you will need to do some work...
And not even sure this will solve what you looking for?
Used something kind of like this to talk from Admin servers on Production servers...
But I wasn't passing the session itself...
Good Luck
There are 6 techniques to manage states in ASP.NET 3.5 (as far as I know).
(1) View State
(2) Cross Page Posting
(3) Query String
(4) Session State
(5) Application State
(6) Cookies
Can anyone give me some appropriate examples of situations where I should use these techniques?
For example:
(*) Session State: Personalization, Buy Cart, etc.
(*) Cookies: Saving User Credentials, etc.
There's a lot of factors that can influence this, so I won't comment on all of them. But here are a few pointers:
ViewState - This is useful when you'll be posting back to the same page frequently (something you're practically forced into doing by ASP.Net Webforms). How useful it is exactly changes depending on what kind of app you're building. For public internet sites, it should be used very sparingly. You may even want to turn it off by default. For local intranet sites, it's a great tool — especially for the fewer, heavier, webforms pages.
Query String - Use this to store state that you need to allow the user to bookmark a page or process and come back to much later. Even then, you might want to keep it down to some kind of hash that you can use as a key in a database lookup to avoid a really huge url (though hashes have their own problems). Also, a lot of users like to fiddle with your query string directly, so it can be dangerous to put too much here. It's easy to accidentally expose data to users who aren't supposed to see it this way.
Application State - Remember that this is shared by all users, so use appropriately. Things like view counts can go here.
Cookies - Don't use cookies to store user credentials. They're just plain unencrypted text files. Use cookies to store a key into the session (even here you can and should now use cookie-less sessions) and simple personalization settings that will be specific to that user and browser. For example, my monitor size at work is different from home, and so putting display size/layout settings into a cookie is nice because the settings stick for each computer, but it isn't going to compromise my security any if someone else reads that information.
Now I want to highlight this concept from the "Query String" section:
you might want to keep it down to some kind of hash that you can use as a key in a database lookup
Again, hashes have their own problems, but I want to point out that several items on my list talk (including Query String) about uploading data from the client web browser to the web server: ViewState, Query String, Cookie, and Cross-Page Post. You want to minimize the data that you move from client to server. This concept applies to all of these, and for several reasons:
Pulling data from the client is slow for public internet sites. Even broadband connections typically cripple the bandwidth available for upload. 512Kpbs (still a typical broadband upload rate in many areas) is nothing when compared to the Gigabit Ethernet (or faster) connection that likely sits between your database and your web server. As much as you might think of a database query as slow (and it is), it's still likely a much better way to go than waiting for the same data to arrive from the client.
Keeping the data on the server is cheaper, because you don't pay for the bandwidth required to push it to or from the client, and bandwidth often costs as much or more than your server hardware.
It's more secure, because if done right even when a client's computer or connection is compromised all the hacker has access to initially is a hash key that likely expires by the time he can decrypt it. Of course, if done wrong he can use that key directly immediately, so you still need to be careful.
So for most things, what I recommend is to start out by keeping a database key in the Session and then have code to easily pull what you need from a database based on that key. As you experience bottlenecks, profile to find out where they are and start caching those pages or controls, or keep that data/query result in the session directly.
State management option
View state:
Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Control state:
Use when you need to store small amounts of state information for a control between round trips to the server.
Hidden fields:
Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.
You can use a hidden field only on pages that are submitted to the server.
Cookies:
Use when you need to store small amounts of information on the client and security is not an issue.
Query string:
Use when you are transferring small amounts of information from one page to another and security is not an issue.
You can use query strings only if you are requesting the same page, or another page via a link.
Server Side Management Options
Application state
Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state
Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Profile properties
Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Database support
Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.
Not sure if you mean the Cache object by Application State.
The Cache object is a great way to manage application wide state, e.g. to record source and count access to your website (to prevent DDOS attacks for example).
(3) Query String
(4) Session State
(5) Application State
(6) Cookies
1. Viewstate
Disclaimer: Use as little as possible. Good point is to always have each state reachable by an url, if possible.
F.e. Paging should use the URL (so /url/?p=2 instead of storing the page in Viewstate)
Use to persist control state between page-cycles.
F.e. Store the selected item in a checkbox, so you can determine whether it has changed.
2. Cross Page Posting
Don't. See the disclaimer for viewstate. Use the URL for this, or store the data in a session / cookie / profile if loads of properties need to be kept around.
Major downside of CPP is that the user cannot use the 'Back' and 'Forward' buttons in it's webbrowser. When a user clicks the back button it wants to undo everything on that page and retry the last one. When using CPP to click them through a wizard; this behavior is not possible without a lot of 'Are you sure you want to resend blablablabl'.
3. Query String
Use alot. Every visible state that a page could reach should be accessible by URL. People with screenreaders will thank you for this. And by using the query string there is no need to use javascript-only solutions.
/url/?page=2 // when doing paging, don't use postback for this
/url/?tab=advanced-search // when having tabs on top of your page
etc.
4. Session state
Use this for short-living objects, that only make sense this time the visitor visits your site. For example:
Which step of a certain wizard was reached
Pages a user had visited before
Small objects you want to put in cache, but that are user-bound
Don't use sessions but profiles for things like:
Preferences
Selected language
Because those things also make sense the next time the user visits your site.
5. Application state
Never. Use ASP.NET cache, or memcached, or any caching framework for this.
6. Cookies
Session ID, Profile ID for authenticated users; user preferences for anonymous users (everything listed in the second list under 4.).
Writting an asp.net shopping cart. I am leveraging the session for state but I also want to store basic info in a cookie. This info would be the items / qty. I am aware of the cookie size limitations but here the question.
Are there any sources of information on performance cost in terms of writting to a cookie as opposed to sql. In my current use case, I would at most be writting to the cookie on each page post (of course only the pages that had to deal with the shopping cart)
Just trying to determine the negative sides to using a cookie.
There are too many factors at play to be able to answer that question.
How fast is your database? How fast is the network? How fast is the end users network connection?
In general: cookies are reasonably fast enough.
But so is a well constructed database call.
I look at other factors when making this call. Cookies can go away, they timeout, and you generally have no real control over them. Is that a problem? If yes, then do sql. If not, then do a cookie. Is security of the data an issue? If yes then do sql.
BTW: Most shopping carts that I've done use sql for most of that data.
In my experience writing a cookie is a lot less cost than making a database call but how much data do you want to store and does it break the functionality if the client blocks cookies?
If you wish to persist session using a cookie, why not make an identifier cookie once when they arrive first time for the user and store this id on the session data. then when a session ends without saving the basket (i.e. on the session end event) flush the session data to the DB with the cookie identifier. Then when the user returns to the site later offer to restore their last basket from the DB by getting the cookie identifier.