16
public string GetCartId(HttpContextBase context)
{
    if (context.Session[CartSessionKey] == null)
    {
        if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
        {
            context.Session[CartSessionKey] =
                context.User.Identity.Name;
        }
        else
        {
            // Generate a new random GUID using System.Guid class
            Guid tempCartId = Guid.NewGuid();
            // Send tempCartId back to client as a cookie
            context.Session[CartSessionKey] = tempCartId.ToString();
        }
    }

    return context.Session[CartSessionKey].ToString();
}        

Any help on the work around with HttpContextBase in asp.net core? above is my sample code am working on to create a shopping cart.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Abel Masila
  • 736
  • 2
  • 7
  • 25

3 Answers3

40

There is no HttpContextBase in ASP.NET Core. HttpContext is already an abstract class (see here) which is implemented in DefaultHttpContext (see GitHub). Just use HttpContext.

Tseng
  • 61,549
  • 15
  • 193
  • 205
2

I had to modify like below

public string GetCartId(HttpContext context)
{
    if (context.Session.GetString(CartSessionKey) == null)
    {
        if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
        {
            context.Session.SetString(CartSessionKey, context.User.Identity.Name);
        }
        else
        {
            var tempCartId = Guid.NewGuid();
            context.Session.SetString(CartSessionKey, tempCartId.ToString());
        }
    }

    return context.Session.GetString(CartSessionKey);
}

It may help someone :)

dnxit
  • 7,118
  • 2
  • 30
  • 34
1

using net5 and autofac I found the following solved my needs. something feels a bit hackish about this and I will update if this solution evolves.

  • add binding for HttpContextAccessor to autofac

          using Microsoft.AspNetCore.Http;
          // ...
          builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>()
              .AsSelf()
              .SingleInstance();
    
  • add dependency to HttpContextAccessor in

    private readonly HttpContextAccessor _httpContextAccessor;
    
  • access current context _httpContextAccessor.HttpContext

workabyte
  • 3,496
  • 2
  • 27
  • 35