如何从HttpContext.Current访问TempData?
解决方法
如果您希望通过自己的设计决策将上下文对象作为参数传递,但您至少可以在自己的全局静态类中使用[ThreadStatic].这对于访问属性的成员来说可以方便,而这些成员又必须依赖于这样的ThreadStatic参数,因为它们不是函数.
ThreadStatic可以帮助在同一线程上共享资源到远程堆栈帧,而无需传递参数. HttpContext.Current使用ThreadStatic来实现这一点.
一个常规的MVC控制器类不会为你做这个.因此,您将需要为项目中的所有控制器创建自己的类,以继承.
public class MyController : Controller { public MyController() { _Current = this; } [ThreadStatic] public static RacerController _Current = null; public static RacerController Current { get { var thisCurrent = _Current; //Only want to do this ThreadStatic lookup once if (thisCurrent == null) return null; var httpContext = System.Web.HttpContext.Current; if (httpContext == null) //If this is null,then we are not in a request scope - this implementation should be leak-proof. return null; return thisCurrent; } } protected override void Dispose(bool disposing) { _Current = null; base.Dispose(disposing); } }
用法:
var thisController = MyController.Current; //You should always save to local variable before using - you'll likely need to use it multiple times,and the ThreadStatic lookup isn't as efficient as a normal static field lookup. var value = thisController.TempData["key"]; thisController.TempData["key2"] = "value2";