Why would ASP.NET MVC use session state? - asp.net-mvc

Recommended by the ASP.NET team to use cache instead of session, we stopped using session from working with the WebForm model the last few years. So we normally have the session turned off in the web.config
<sessionState mode="Off" />
But, now when I'm testing out a ASP.NET MVC application with this setting it throws an error in class SessionStateTempDataProvider inside the mvc framework, it asked me to turn on session state, I did and it worked. Looking at the source it uses session:
// line 20 in SessionStateTempDataProvider.cs
Dictionary<string, object> tempDataDictionary =
httpContext.Session[TempDataSessionStateKey] as Dictionary<string, object>;
So, why would they use session here? What am I missing?
========================================================
Edit Sorry didn't mean for this post to debate on session vs. cache, but rather in the context of the ASP.NET MVC, I was just wondering why session is used here. In this blog post also Scott Watermasysk mentioned that turning off session is a good practice, so I'm just wondering why I have to turn it on to use MVC from here on.

Session is used for the TempData store. TempData is a highly limited form of session state which will last only until the next request from a certain user. (Edit In MVC 2+, it lasts until it is next read.) The purpose of TempData is to store data, then do a redirect, and have the stored data be available to the action to which you just redirected.
Using Session for the TempData store means that any distributed caching system which already handles Session will work for TempData. Avoiding using Session directly when TempData will do has a couple of advantages. One is that you don't have to clean up the Session yourself; TempData will "expire" on its own.

Recommended by the ASP.NET team to use
cache instead of session
#ray247, could you provide a reference for this? Session and Cache are different by nature and should be used depending on application requirements. For example storing user specific data into the cache could lead to undesired behavior. Of course if you really want to avoid using session you could provide your own implementation of the ITempDataProvider interface.

Hmm... May be you've read about persisting of the heavy objects or relatively rarely accessed objects - it's definitely better to put them into cache, but for light objects or for data that is required at every request there is no better technique than put them into Session.
Sessions are not evil if you are using them correctly.

Just an additional thought. TempData has its own purpose and MS knew there will be different school of thoughts with respect to TempData persistent mechanism. So, by default they made the persistent store to be SessionState. But the design is still very flexible. Based on the needs of the project and the governance that guides it you can create your own tempdata provider to suit specific requirements.
Here are some pointers to the resources
TempData
Here are some additional improvements in TempData implementation
TempData Improvements
Here's an alternative implementation using MS Velocity Distributed Caching.
Velocity TempData Provider

Related

Is TempData in ASP.NET MVC secure?

I want to know about security of tempdata in ASP.NET MVC in the following scenario.
If one user is logged in and there is data passed to tempdata and it is we are keeping for next request or we are not reading it so it keeps value in tempdata. If another user logged in, then will that tempdata value also be available to the second user?
TempData uses by default Session*. Therefore it is as safe as a session can be.
A session is individual for every user, so yes.
Session Hijacking is one problem for a session, but since TempData is only valid for one request, I do not see any problems.
* Note it is possible to create a own ITempDataProvider (Credits to NightOwl888). In this case, you need to evaluate, if your provider is secure.

.net mvc authentication cookies & sessions

net mvc 5 application using entity frame work etc and am new to .net c# etc (used to php & sessions)
so i have read allot about using .nets authentication service and that is some how registers a user upon login using FormsAuthentication.SetAuthCookie.
however i need to authenticate a user group for example admin or moderator. and from what i understand this can be achieved and be set using [authenticate(roles="admin")].
but surely if this is using a set cookie a user if they knew how could just change their registered role from user to admin to access restricted content?
so in as simple terms as possible how does .net mvc ensure security in authenticating users? can i use sessions instead of cookies? do i need to create my own authentication system.?
i have searched and read all i can find and most resources just explain how cookies work or how to implement authentication using cookies but very little about sessions.
I'll try to be as concise as possible:
Yes, ASP.NET MVC 5 uses cookies out of the box (if you chose Individual User Accounts in the project wizard)
The authorization of a group or role by means of an [Authorize(Roles="bla")] attribute to decorate controllers and/or controller methods will do just that. It's as if you would be writing
if(!User.IsInRole("bla"))
{
return new HttpUnauthorizedResult();
}
else
{
//here's your ultra-secret View
return View();
}
What if a user changes role while in-session or if he or she has a persistent cookie?
Indeed, you'll need to handle the interval between role change and cookie update.
Read up on it here
Long story short: the design decision is yours whether you think it better to log off a user when re-assigning roles or to make db roundtrips at every authorization check.
Can you use a session variable like in PHP? Sure (the Session object exists), but you shouldn't.
If and when the situation arises where you absolutely NEED to pass some arbitrary data however, there's ViewBag, ViewData and TempData.
I won't go as far as to say, that these constructs are superfluous, they certainly have their use from time to time, but do try and design your application to maximize the use of strongly-typed models, viewmodels and make use of the REST-based url architecture to get or put your data.

asp.net mvc and web farm

given the nature of the project, I need to store a simple object (with 3/4 properties) in TempData. It is a read once write once so that's fine but does need to be passed between a few core methods/actions.
question is: How can I make it work with webfarms? What things are needed to be configured to allow TempData to work with a webfarm?
using MVC 4 Razor.
thank you
By default, TempData is implemented using Sessions, so this would be a problem on a farm.
The easiest solution would be to use the CookieTempDataProvider
TempData is stored in the session. This means that the only reliable way to use it in a web farm would be to have a state server of some sort.
Changing the ApplicationId (MachineKey) on all the servers to make them match does nothing for session. That only means that each server can decode the cookies left by the others. Session lives on the individual web server in memory.
If you don't have sticky sessions on your load balancer, the request that populates TempData on server 1, will likely redirect to a server different than itself and TempData will not be populated (or not with the same data that was just put in on server 1).

Where does TempData get stored?

Where does TempData get stored in the ASP.NET MVC Framework (more specifically, ASP.NET MVC 2)? Is it stored at server-side, or is sent to the client?
By default TempData uses the ASP.NET Session as storage. So it is stored on the server (InProc is the default). But you could define other ASP.NET Session state modes: StateServer and SqlServer. You could also write a custom TempData provider and handle the storage yourself if you don't want to use the ASP.NET Session.
It is stored in session storage, but there is one crucial difference between TempData and Session:
TempData is available only for a user’s session, so it persists only till we have read it and gets cleared at the end of an HTTP Request.
A scenario that fits the usage of TempData, is when data needs to persist between two requests – a redirect scenario. Another scenario I can think of is to return an error message after a POST operation fails.

How can I store user data after login without having to query the database to show this data?

I need to store the user ID, his company ID and name, in a way I won't have to query the database on every postback.
I know I have options like: ViewData, TempData or auth cookie, but, are there any better solution?
Best regards,
Juliano Nunes
This sounds like a classic use of Session.
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.
ASP.NET Profile Providers mechanism looks like a thing you're looking for - especially if you're already using Membership/Role providers.
More generic article on Profile properties: MSDN

Resources