如何访问 startup.cs 文件中的 TempData?

How to access the TempData in the startup.cs file?

我在 startup.cs 文件 (Razor Pages) 中有一个中间件,想检查 TempData 中是否存在某个值,但我找不到访问 TempData 的方法。我正在走向坏习惯吗?如果是这样,我如何在我的中间件中读取运行时产生的值?

你可以尝试使用ITempDataDictionaryFactory,这里有一个演示:

中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
                ITempDataDictionaryFactory factory = context.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
                ITempDataDictionary tempData = factory.GetTempData(context);
                //get or set data in tempData
                var TestData=tempData["TestData"];
                // Do work that doesn't write to the Response.
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });
       }

家庭控制器:

public class HomeController : Controller
    {
        
        public IActionResult Index()
        {
            TempData["TestData"] = "test";
            return View();
        }

       
    }

结果: