Search code examples
c#asp.net-mvcsession-state

Access HttpContextBase object from static class


ASP.NET 4.6.1 using MVC 5.

I have a class with the following constructor and I'm setting a session variable:

public class MyClass()
{
    private HttpContextBase Context { get; set; }

    public MyClass(HttpContextBase context)
    {
        Context = context;
    }

    public bool CheckForAccess()
    {
        Context.Session["MyVariable"] = "Hello";
        return true;
    }
}

I can access the session and pass it to my object from my controller like so:

public ActionResult Index()
{
    var myclass= new MyClass(HttpContext);
    var excluded = myclass.CheckForAccess();
}

This is working fine. Now i have a static class and i need to call the same function in MyClass:

public static class MyClassExtension
{
    public static bool Check()
    {
   //here's where i'm stuck
    var myclass = new MyClass(I_need_to_pass_the_HttpContextBase_from_here);
        return myclass.CheckForAccess();
    }
}

This is where i'm stuck. I'm clearly trying to access the current session of the logged in user and pass it around when i have to. What do i pass from my static class to the constructor of with an HttpContextBase parameter so it can be used in the MyClass object? Thanks


Solution

  • You can use HttpContext.Current, but beware: if the static is called outside of the ASP.NET request, HttpContext.Current will be null (or may be null in certain situations depending on how you are using this):

    public static bool Check()
    {
        var myclass = new MyClass(new HttpContextWrapper(HttpContext.Current));
        return myclass.CheckForAccess();
    }
    

    HttpCOntextWrapper exists to wrap the old HttpContext sealed class and support the HttpContextBase base class.