How can I disable session state in ASP.NET MVC?

▼魔方 西西 提交于 2019-11-26 19:35:28

You could make your own ControllerFactory and DummyTempDataProvider. Something like this:

public class NoSessionControllerFactory : DefaultControllerFactory
{
  protected override IController GetControllerInstance(Type controllerType)
  {
    var controller = base.GetControllerInstance(controllerType);
    ((Controller) controller).TempDataProvider = new DummyTempDataProvider();
    return controller;
  }
}


public class DummyTempDataProvider : ITempDataProvider
{
  public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
  {
    return new Dictionary<string, object>();
  }

  public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
  {
  }
}

And then you would just need to register the controller factory on app startup - e.g. you could do this in global.asax:

ControllerBuilder.Current.SetControllerFactory(new NoSessionControllerFactory());

I've found one way, which I don't particularly care for:

Create NoTempDataProvider

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Facebook.Sites.Desktop.Auth.Models
{
    public class NoTempDataProvider : ITempDataProvider
    {
        #region [ ITempDataProvider Members ]

        public IDictionary<String, Object> LoadTempData(ControllerContext controllerContext)
        {
            return new Dictionary<String, Object>();
        }

        public void SaveTempData(ControllerContext controllerContext, IDictionary<String, Object> values) { }

        #endregion
    }
}

Manually Overwrite the Provider in the Controller

public class AuthController : Controller
{
    public AuthController()
    {
        this.TempDataProvider = new NoTempDataProvider();
    }
}

I would greatly prefer a way to do this completely via the configuration, but this works for now.

If you need to use TempData for simple strings, you can use the CookieTempDataProvider in MvcFutures http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471.

According to Brad Wilson, this has been fixed in MVC 2 Preview 1. See here and here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!