0

an object reference is required to access non-static field, method or property

When I make the GetCartId static Visual Studio complains

public class Uno
{
    private readonly HttpContext context;

    public Uno()
    {
    }

    public Uno(HttpContext _context)
    {
        context = _context;
    }
    public static string GetCartId()
    {
        string cartId = "";
        var stringId = context.Session.GetString("cart");
        if(stringId == null)
        {
            cartId = Guid.NewGuid().ToString();
            stringId = cartId;
        }
        else if(stringId != null)
        {
            cartId = stringId;
        }
        return cartId;
    }
}
Rampp
  • 1
  • 1
  • 5
  • 1
    @poke, I was wrong to vote-close this one with general "access instance member from static" question. This question is rather `HttpContext.Current` related. – Sinatr Jul 26 '16 at 09:42

2 Answers2

3

You are accessing context from that method. It needs to be static in order to be able to use it:

private static readonly HttpContext context;

readonly doesn't make it static. It is readonly on instance level. (const on the other hand is static by definition)

I would warn you though to use static with a HttpContext since static is shared across instances in ASP.NET. You might end up mixing user sessions!

Use HttpContext.Current from the static method itself.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

context is not static so you cant access it from a static method without an instance of Uno. But even then you can't access it because it's private.

Instead I would use HttpContext.Current which works even in a static method:

public static string GetCartId()
{
    var context = HttpContext.Current;
    if(context == null) return null;
    string cartId = "";
    var stringId = context.Session.GetString("cart");
    if(stringId == null)
    {
        cartId = Guid.NewGuid().ToString();
        stringId = cartId;
    }
    else if(stringId != null)
    {
        cartId = stringId;
    }
    return cartId;
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939