如何在我自己的实用程序 class 中访问 TempData?或者构造函数中的 TempData 为 null
How to access TempData in my own utility class? Or TempData is null in constructor
我在我的某些 Views/Actions 中使用了 TempData,但我想将其提取到某些 class 中。问题是如果我尝试在 Controller 的构造函数中创建我的 class,那里的 TempDate 为 null。更好的是,我想让我的 class 可以注入到 Controller 中。所以我需要在创建 class 时访问 TempData。
那么这个TempData如何在单独的class中构建呢?
这是 ASP.NET 核心 2.0 网络应用程序。
您可以通过简单地注入 ITempDataDictionaryFactory
where you need it. You can then call its GetTempData
which returns an ITempDataDictionary
来访问任何地方的临时数据,您可以使用它来访问(读取或写入)当前 HTTP 上下文的临时数据:
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";
}
}
顺便说一句。在控制器的构造函数中 TempData
是 null
的原因是因为控制器上下文仅在控制器创建后才注入(使用 属性 注入)。所以当控制器的构造函数运行时,根本就没有关于当前请求的任何信息。
如果你确实注入了你的服务,并且该服务像上面的 ExampleService
一样工作,那么它甚至可以在构造函数中工作,因为它只会从 DI 容器本身请求必要的信息(工厂和 HTTP 上下文)。
我在我的某些 Views/Actions 中使用了 TempData,但我想将其提取到某些 class 中。问题是如果我尝试在 Controller 的构造函数中创建我的 class,那里的 TempDate 为 null。更好的是,我想让我的 class 可以注入到 Controller 中。所以我需要在创建 class 时访问 TempData。
那么这个TempData如何在单独的class中构建呢?
这是 ASP.NET 核心 2.0 网络应用程序。
您可以通过简单地注入 ITempDataDictionaryFactory
where you need it. You can then call its GetTempData
which returns an ITempDataDictionary
来访问任何地方的临时数据,您可以使用它来访问(读取或写入)当前 HTTP 上下文的临时数据:
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";
}
}
顺便说一句。在控制器的构造函数中 TempData
是 null
的原因是因为控制器上下文仅在控制器创建后才注入(使用 属性 注入)。所以当控制器的构造函数运行时,根本就没有关于当前请求的任何信息。
如果你确实注入了你的服务,并且该服务像上面的 ExampleService
一样工作,那么它甚至可以在构造函数中工作,因为它只会从 DI 容器本身请求必要的信息(工厂和 HTTP 上下文)。