Question

I was trying to make one site as session less. So add <sessionState mode="Off" /> to my web.config. After that if I execute

 Session["test"] = "yes"; 

I get an error “Object reference not set to an instance of an object.” This is fine.

But with this configuration I can set

TempData["test"] = "yes"; 

in controller and print TempData["test"]; in View page. It is working well.

As per MSDN “The TempData property value is stored in session state”.

So if I mention <sessionState mode="Off" /> how TempData is working? Is ASP.NET still storing TempData in session or somewhere else?

Was it helpful?

Solution

This can work with disabled session state only if you are printing TempData["test"] on your View during the same request - thus this value is removed from the TempData dictionary and MVC is not trying to save it to the session state. Try to remove it from your view and you'll get System.InvalidOperationException: The SessionStateTempDataProvider class requires session state to be enabled.

You can individually disable session state for your controllers by adding [SessionState(SessionStateBehavior.Disabled)] attribute or implementing your own TempData provider using ITempDataProvider interface.

[EDIT] Just to explain my first point, let's imagine two situations:

  • You have controller action that assigns some value to TempData["test"] and a corresponding view that is being returned from this action and prints this data. In this case everything will be working even without a session state because there is no need to store TempData["test"] between requests.
  • You have controller action that assigns some value to TempData["test"] but redirects user to another action with its own view that prints this data. In this case it will not work with session state disabled as MVC needs to store your TempData["test"] value between two requests.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top