这段代码可以很好地从控制器中获取会话ID:
sys.maxsize == (2 ** 31 - 1)
...但是当我尝试在视图组件类中放入相同的代码时,VS告诉我名称HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
(或仅HttpContext.Session.SetString
,或只是HttpContext.Session
)在当前的背景下不存在。我在课程顶部有HttpContext
。
修改
这是我的视图组件类:
using Microsoft.AspNetCore.Http;
答案 0 :(得分:2)
问题是您正在尝试访问HttpContext
实例上存在的方法,而不是静态方法。最简单的方法是让依赖注入框架为您提供IHttpContextAccessor
。例如:
public class ShoppingCartViewComponent : ViewComponent
{
private readonly IHttpContextAccessor _contextAccessor;
private readonly MyStoreContext _context;
public ShoppingCartViewComponent(MyStoreContext context,
IHttpContextAccessor contextAccessor)
{
_context = context;
_contextAccessor = contextAccessor;
_contextAccessor.HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = _contextAccessor.HttpContext.Session.Id;
}
//snip rest of code for brevity
}