从视图组件中获取会话 ID

Getting the session Id from within a view component

这段代码可以很好地从控制器中获取会话 ID:

HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;

...但是当我尝试将相同的代码放入视图组件 class 时,VS 告诉我名称 HttpContext.Session.SetString(或只是 HttpContext.Session,或者只是 HttpContext) 在当前上下文中不存在。我在 class 的顶部有 using Microsoft.AspNetCore.Http;

编辑

这是我的视图组件 class:

public class ShoppingCartViewComponent : ViewComponent
{
    private readonly MyStoreContext _context;

    public ShoppingCartViewComponent(MyStoreContext context)
    {
        _context = context;
    }

    // Initialize session to enable SessionId
    // THIS WON'T WORK:
    HttpContext.Session.SetString("_Name", "MyStore");
    string SessionId = HttpContext.Session.Id;

    public async Task<IViewComponentResult> InvokeAsync(int Id)
    {
        var cart = await GetCartAsync(Id);
        return View(cart);
    }

    private async Task<ViewModelShoppingCart> GetCartAsync(int Id)
    {
        var VMCart = await _context.ShoppingCarts
                    .Where(c => c.Id == Id)
                    .Select(cart => new ViewModelShoppingCart
                    {
                        Id = cart.Id,
                        Title = cart.Title,
                        CreateDate = cart.CreateDate,
                        ShoppingCartItems = cart.ShoppingCartItems
                                            .Select(items => new ViewModelShoppingCartItem
                                            {
                                                ProductId = items.ProductId,
                                                ProductTitle = items.Product.Title,
                                                ProductPrice = items.Product.Price,
                                                Quantity = items.Quantity
                                            }).ToList()
                    }).FirstOrDefaultAsync();
        return VMCart;
    }
}

问题是您正在尝试访问存在于 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    
}