您可以创建自己的ControllerFactory和DummyTempDataProvider。像这样:
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)
{
}
}
然后,您只需要在应用启动时注册控制器工厂-例如,您可以在global.asax中执行以下操作:
ControllerBuilder.Current.SetControllerFactory(new NoSessionControllerFactory());