1

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?

3
  • What are you trying to do? What kind of value are you trying to access inside a middleware? Commented Jun 19, 2021 at 8:01
  • Please show us what you've done so far. BR Commented Jun 19, 2021 at 19:04
  • I store some values that are used throughout the app in the TempData. There are cases where TempData expires or are empty. I just want to see if there is a way to check the TempData outside of a Razor Page. Commented Jun 20, 2021 at 12:31

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Can you accept it as an answer?Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.