从视图组件中获取会话 ID

Sti*_*ian 2 c# session asp.net-core asp.net-core-viewcomponent

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

HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
Run Code Online (Sandbox Code Playgroud)

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

编辑

这是我的视图组件类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 5

问题是您正在尝试访问存在于 实例上的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    
}
Run Code Online (Sandbox Code Playgroud)