I have implemented a middleware in my mvc web application that retrieves all user data from the database and sets it in the session object.
However, since the middleware is called on each HTTP session,
I want to ensure that this logic executes only once per session.
Here is my current implementation:
public async Task InvokeAsync(HttpContext context)
{
if (context.Session.Get("sessionWasInitialized") != null)
{
// Session was initialized, finish this task
await _next(context);
return;
}
// This Key will make sure that the session was initialized once per session
context.Session.SetString("sessionWasInitialized", "true");
// Get user data from DB and set the Session object...
// .........
//
await _next(context);
}
虽然这种方法似乎奏效了,但I'm wondering if there is a more efficient or elegant way to achieve the same behavior.如果有任何建议或替代方法来处理这种情况,我将不胜感激.