BowserKingKoopa
BowserKingKoopa

Reputation: 2741

Accessing TempData from HttpContext.Current

How can I access TempData from HttpContext.Current?

Upvotes: 12

Views: 7960

Answers (3)

Kind Contributor
Kind Contributor

Reputation: 18583

If you want to do this without passing the context object as a parameter due to your own design decisions, you can at least use [ThreadStatic] on your own global static class. This can be convienient for Property accessed members which in turn must rely on such a ThreadStatic parameter, as they are not functions.

ThreadStatic can help share resources on the same thread to distant stack frames without needing to pass parameters. HttpContext.Current uses ThreadStatic to achieve this.

A regular MVC Controller class will not do this for you. So you will need to create your own Class for all Controllers in your project to inherit from.

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);
  }
}

Usage:

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";

Upvotes: 1

Mike
Mike

Reputation: 7701

Addressing your comment to the other answer, you might implement your own ITempDataProvider and then override Controller to use it. Take a look at the CookieTempDataProvider class in Mvc3Futures which stores tempdata in cookies rather than session to see how this is possible.

http://volaresystems.com/Blog/post/2011/06/30/Sessionless-MVC-without-losing-TempData.aspx

Rather than changing where tempdata is stored, your implementation could possible inherit from SessionCookieTempDataProvider and simply add type-safe methods to it.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You can't/shouldn't access TempData from HttpContext.Current. You need a controller instance. Unfortunately because you haven't explained your scenario and why do you need to do this I cannot provide you with a better alternative.

Upvotes: 1

Related Questions