You can access temp data anywhere by simply injecting ITempDataDictionaryFactory
where you need it. You can then call its GetTempData
which returns an ITempDataDictionary
which you can use to access (read or write) the temp data for the current HTTP context:
public class ExampleService
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public ExampleService(IHttpContextAccessor httpContextAccessor, ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_httpContextAccessor = httpContextAccessor;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public void DoSomething()
{
var httpContext = _httpContextAccessor.HttpContext;
var tempData = _tempDataDictionaryFactory.GetTempData(httpContext);
// use tempData as usual
tempData["Foo"] = "Bar";
}
}
Btw. the reason why TempData
is null
in your controller’s constructor is because the controller context is only injected after the controller has already been created (using property injection). So when the controller’s constructor runs, there simply isn’t any information about the current request yet.
If you do inject your service though, and that service works like the ExampleService
above, then it will work even from within the constructor, since it will simply request the necessary information from the DI container itself (the factory and the HTTP context).