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?
-
What are you trying to do? What kind of value are you trying to access inside a middleware?abdusco– abdusco2021-06-19 08:01:33 +00:00Commented Jun 19, 2021 at 8:01
-
Please show us what you've done so far. BRRoar S.– Roar S.2021-06-19 19:04:57 +00:00Commented 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.StaPantazis– StaPantazis2021-06-20 12:31:08 +00:00Commented Jun 20, 2021 at 12:31
Add a comment
|
1 Answer
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();
}
}
1 Comment
Yiyi You
Can you accept it as an answer?Thank you.
