Search code examples
c#sessionasp.net-coreasp.net-core-viewcomponent

Getting the session Id from within a view component


This piece of code works fine to get the session Id from within the controller:

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

... but when I try to put the same code in a view component class, VS tells me that the name HttpContext.Session.SetString (or just HttpContext.Session, or just HttpContext) does not exist in the current context. I have using Microsoft.AspNetCore.Http; at the top of the class.

edit

Here is my view component 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;
    }
}

Solution

  • The problem is that you are trying to access a method that exists on an instance of HttpContext, not a static method. The easiest way is to let the depenancy injection framework give you a IHttpContextAccessor. For example:

    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    
    }