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

问题描述

我在 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();
        }

       
    }

结果: enter image description here