如何从HttpContext.Current访问TempData?从HttpContext.Current访问TempData
回答
您不能/不应该从HttpContext.Current
访问TempData
。你需要一个控制器实例。不幸的是,因为你没有解释你的情况,为什么你需要这样做,我不能为你提供一个更好的选择。
我正在创建一个以更友好/类型安全的方式包装TempData的类。它在内部使用TempData,但我不想公开这个事实。我不想在像'new MyTempDataWrapper(this.TempData)'中传递TempData。如果TempData只存储在Session中,并且Session可以从HttpContext.Current访问,为什么我不能从HttpContext.Current访问TempData? – BowserKingKoopa 2011-03-26 20:05:51
将您的评论发送给其他答案,您可以实现自己的ITempDataProvider,然后重写控制器以使用它。看一下Mvc3Futures中的CookieTempDataProvider类,它将tempdata存储在cookie而不是会话中,以查看这是如何实现的。
http://volaresystems.com/Blog/post/2011/06/30/Sessionless-MVC-without-losing-TempData.aspx
而不是改变的TempData存储在何处,您的实现可以从SessionCookieTempDataProvider可能继承和简单的添加类型安全的方法吧。
如果由于自己的设计决定而不传递上下文对象作为参数,那么您至少可以在您自己的全局静态类上使用[ThreadStatic]。对于Property访问的成员来说,这可能会很方便,而这些成员又必须依赖这样的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";
- 1. 访问TempData变量
- 2. 从WCF Web服务访问HttpContext.Current
- 3. 访问数据访问层中的HttpContext.Current
- 4. 如何从HttpContext.Current
- 5. 在javascript中访问tempdata在mvc4
- 6. 在定制中间件中访问TempData
- 7. 设置tempdata从Global.asax
- 8. 为什么通过HttpContext.Current访问会话不好[练习]?
- 9. C#ASP.NET:如何访问缓存时没有HttpContext.Current可用(为空)?
- 10. Moq'ing HttpContext.Current
- 11. ASP.Net MVC - TempData会话问题
- 12. TempData的问题镀铬
- 13. .NET Remoting和HttpContext.Current
- 14. HttpContext.Current VS ActionExecutingContext
- 15. HttpSelfHostServer和HttpContext.Current
- 16. HttpContext.Current返回null
- 17. Parallel.ForEach错误HttpContext.Current
- 18. HttpContext.Current无法序列
- 19. ASP.NET HttpContext.Current在Task.Run中
- 20. 可能愚弄HTTPContext.Current?
- 21. 的TempData在FileContentResult
- 22. TempData:安全吗?
- 23. 避免TempData MVC
- 24. TempData&Redirect for Errors
- 25. MVC TempData issue
- 26. TempData和模式
- 27. 从非控制器类添加到TempData
- 28. TempData从视图移动到控制器
- 29. 访问从View
- 30. 访问从HOC
你找到解决这个问题呢? – trailmax 2013-10-01 23:54:37