Search code examples
c#asp.net-mvcasp.net-corerazortempdata

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


I have a Middleware in the startup.cs file (Razor Pages) and want to check whether a value exists in the TempData, but I cannot find a way to access the TempData. Am I heading towards a bad practice? If so, how could I read a runtime-produced value in my Middleware?


Solution

  • You can try to use ITempDataDictionaryFactory,Here is a demo:

    Middleware:

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

    HomeController:

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

    result: enter image description here