【问题标题】:Asp.Net Core 2.0 session in service is null throws exception [duplicate]服务中的 Asp.Net Core 2.0 会话为空抛出异常 [重复]
【发布时间】:2017-09-06 01:24:38
【问题描述】:

我正在尝试在我的服务中添加会话

 private readonly ApplicationDbContext _context;
 private readonly ISession _session;


    public CartService(ApplicationDbContext context, IServiceProvider serviceProvider)
    {
        _context = context;
        _session = serviceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
    }

在 Startup.cs 中我添加了这一行:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

当我运行应用程序时出现异常:

System.NullReferenceException: '对象引用未设置为对象的实例。'

我不明白,我错过了什么?

【问题讨论】:

    标签: c# asp.net session asp.net-core


    【解决方案1】:

    我通过删除以下行来解决它:

     private readonly ISession _session;
     _session = serviceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
    

    而是在我的方法中将会话作为参数发送

    public List<Item> GetItems(HttpContext httpContext)
        {
         List<Item> Items = new List<Item>();  
            var session = httpContext.Session.GetInt32("Session");
    
         return Items
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多