If you've done much ASP.NET development, you know you shouldn't use session for high performance web sites that require web farms and load balancers. You can centralize session to be on one web server or move it to the database, but what if you want to avoid it altogether?
MVC 3 introduces a new controller attribute called SessionStateAttribute. You can decorate your controller with this attribute to disable session, make it read-only, or turn it on for full read-write access. Note that TempData, which uses session to store values between requests, is also disabled if session is disabled. That makes sense, but since it's called TempData[]
instead of Session[]
, it's not obvious.
Here's how you can use this on a controller. Note this attribute is at the controller level, not the action level.
using System.Web.Mvc;
using System.Web.SessionState;
namespace MvcApplication1.Controllers
{
[SessionState(SessionStateBehavior.Disabled)]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
}
And here's how you can set it as a Global Filter to turn it off for all controllers. The attribute is being set in the RegisterGloablFilters
method in the Global.asax
and is called in Application_Start
.
UPDATE: This doesn't work as a global action filter. However, you can turn off session for your whole application with code in your web.config
like this:
<system.web>
...
<sessionState mode="Off" />
...
</system.web>