我试图在我的服务中添加会话
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:&#39;对象引用未设置为对象的实例。&#39;
我没有得到它,我错过了什么?
答案 0 :(得分:0)
我通过删除以下行解决了这个问题:
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
}