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.如果有任何建议或替代方法来处理这种情况,我将不胜感激.

推荐答案

实际上,从您的代码中,我认为通过会话密钥判断会话是否为空是合理的,并且应该有效地工作.

如果您的项目中的会话仅针对此情况,则可以使用:

public async Task InvokeAsync(HttpContext context)
{
    if (!context.Session.Keys.Any())
    {
        // Get user data from DB and set the Session object...
        //    .........
        //
    }

    await _next(context);
}

这种方法减少了判断特定密钥的开销.

Csharp相关问答推荐

无法使用命令提示符创建空的dotnet核心Web应用程序

System.Text.Json:反序列化返回为空数组的字典时出错

Blazor:子编辑表单上的嵌套编辑表单验证

在包含空项的列表上使用具有断言T的摘要表

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

EF Core在请求列表时忽略列,但在按ID获取时包含

Entity Framework Core 8 dbcontext—无法以多对多关系添加某些行'

如何使用CsvReader获取给定列索引的列标题?

Unity 2D自顶向下弓旋转

需要澄清C#的Clean Architecture解决方案模板的AuditableEntityInterceptor类

在FilePath中搜索一个词,并根据First Match从左到右提取文件路径

如何使用C#Interop EXCEL创建度量衡

模型绑定RazorPage表单

我想在文本框悬停时在其底部显示一条线

异步等待Foreach循环中的ConfigureAWait(FALSE)执行什么操作?

如何在GRPC代码First服务的返回类型上使用多态性?

Azure函数-在外部启动类中生成配置时出错

ReadOnlyMemory访问基础索引的替代方案

如何正确地在VB中初始化类?

如何在.NET MAUI上在iOS和Mac之间共享代码?(no条件编译和无代码重复)