【问题标题】:HttpContext.Current.Session null with DependencyInjectionProviderHttpContext.Current.Session null 与 DependencyInjectionProvider
【发布时间】:2021-03-31 14:38:26
【问题描述】:

我正在使用 DependencyInjectionProvider,当我检查容器时,我得到一个空会话引用。有人可以告诉我如何解决吗?我的代码如下:

代码 1:

private Container Init()
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
        container.Register<ConnectionString>(() => UserContext.Current?.connectionString ?? new ConnectionString(ConfigurationManager.AppSettings["banco_cliente"]), ScopedLifestyle.Scoped);
        SimpleInjectorContainer.RegisterMvc(container);
        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        container.Verify();
        return container;
    }

代码2(UserContext的属性Current):

public static Current Current
    {
        get
        {
            try
            {
                if (HttpContext.Current.Session["__contexto_do_usuario_logado__"] == null)
                    Inicializar();
                return HttpContext.Current.Session["__contexto_do_usuario_logado__"] as Current;
            }
            catch
            {
                return null;
            }
        }
    }

【问题讨论】:

  • 我不明白第一个代码块中的代码与第二个代码块有什么关系。 Init() 在哪里被调用?你用的是什么依赖注入框架?
  • Init() 是调用给出问题的属性的方法。我认为该插件调用 SimpleInjector。我是 C# 新手,这是我目前工作的公司的一个项目
  • 是否在用户请求的上下文中调用了Init?如果没有,为什么会有 HttpContext?如果是……那么除了应用启动之外,为什么还要创建容器?
  • 你添加UseSession中间件了吗?可能不相关,但要先给出
  • 中间件代码应该放在哪里?我是 ASP.NET 新手,这是我最近加入的一个项目

标签: c# asp.net .net visual-studio


【解决方案1】:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//I'd put this toward the end of the code block but before your routing.
app.UseSession();
}

我认为默认情况下不会启用会话。通过添加这一行,使会话可用。我可能是错的。

【讨论】:

  • 这个文件必须在 Startup.cs 吗?
  • 我假设没有检查......这个解决方案适用于 aspnet.net 核心项目。在您的 startup.cs 中,您将拥有 configure 方法,只需添加行
猜你喜欢
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 2023-03-20
  • 2016-03-10
  • 2015-06-22
相关资源
最近更新 更多