title: Getting the session Id from within a view component
body: <p>This piece of code works fine to get the session Id from within the controller:</p>
  
  <pre><code>HttpContext.Session.SetString("_Name", "MyStore");
  string SessionId = HttpContext.Session.Id;
  </code></pre>
  
  <p>... but when I try to put the same code in a view component class, VS tells me that the name <code>HttpContext.Session.SetString</code> (or just <code>HttpContext.Session</code>, or just <code>HttpContext</code>) does not exist in the current context. I have <code>using Microsoft.AspNetCore.Http;</code> at the top of the class.</p>
  
  <p><strong>edit</strong></p>
  
  <p>Here is my view component class:</p>
  
  <pre><code>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&lt;IViewComponentResult&gt; InvokeAsync(int Id)
      {
          var cart = await GetCartAsync(Id);
          return View(cart);
      }
  
      private async Task&lt;ViewModelShoppingCart&gt; GetCartAsync(int Id)
      {
          var VMCart = await _context.ShoppingCarts
                      .Where(c =&gt; c.Id == Id)
                      .Select(cart =&gt; new ViewModelShoppingCart
                      {
                          Id = cart.Id,
                          Title = cart.Title,
                          CreateDate = cart.CreateDate,
                          ShoppingCartItems = cart.ShoppingCartItems
                                              .Select(items =&gt; new ViewModelShoppingCartItem
                                              {
                                                  ProductId = items.ProductId,
                                                  ProductTitle = items.Product.Title,
                                                  ProductPrice = items.Product.Price,
                                                  Quantity = items.Quantity
                                              }).ToList()
                      }).FirstOrDefaultAsync();
          return VMCart;
      }
  }
  </code></pre>