asp.net-mvc-3 – 从HttpContext.Current访问TempData

如何从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";

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....