Edi
Edi

Reputation: 989

Maintaining state in Asp.Net MVC website

I'm currently designing a new website built on MVC and I wonder what is the right way to manage state.
The state should contain the userId and some structs of the user info, and should be kept during the whole session of the user while he's logged in (across http requests)

The important criteria:
1) Support scalability
2) Performance

The easy way is to use the Session object, but it doesn't support scalability. If different requests during the session go through different IIS servers, the session won't be kept. Although I've heard of load balancing tools which route all requests of a single session through the same machine, I'm not sure that it's a good practice to rely on it (isn't it?)

Another option that I've read about, is keeping the state data in special state servers which are running a RAM DB (like Cassandra for Linux or Redis for Windows). But it seems to me an overkill at this stage of the development.

Do you have any other suggestions? I would like to start with something simple at the moment, but keep the design ready for a more advanced solution at the future.

Any best practice or code/design suggestions will be appreciated.

Thanks,
Edi.

Upvotes: 2

Views: 2091

Answers (2)

Yaakov Ellis
Yaakov Ellis

Reputation: 41490

(1) Use Sql Server to Store Session State

(2) Use Memcached as a Session State Provider

(3) Cook up your own solution using Caching on an external caching provider: look into using something like the ServiceStack Caching Framework. Using this, you can use Redis, Memcached, Azure or AWS to handle caching.

Next, create a KeyFactory to handle generation of keys for specific items. The item keys would include the UserId (which you would always have from FormsAuthentication UserId (assuming that you are using FormsAuthentication). Then store any Session data for the user in the cache. Using this approach you are using Caching in place of Session, and the cache can be shared across multiple servers.

Note: you can have different approaches regarding clearing out the user's data whenever they begin a new session. Potential approaches include:

  • Include the user's session start dateTime in the cacheKey, and auto-expire entries when they are no longer fresh
  • Clear out all potential entries for a user when they begin a new session

Upvotes: 3

Kevin Junghans
Kevin Junghans

Reputation: 17540

If you are using .NET 4.5 and dependent on the type and amount of information you are keeping on users you may want to look at using claims to store information about the user. In .NET 4.5 all Principals inherit from ClaimsPrincipal. ClaimsPrincipal already uses claims to store the user name, roles and other information. You can create your own service to transform claims, which will allow you to add additional information to the Principal user.

Upvotes: 0

Related Questions