Lem
Lem

Reputation: 61

'Session state is not available in this context.' from HttpApplication().Session call

I'm attempting to build a multi-step registration form and have a session to contain data throughout the process. When my application first loads it attempts set a session variable for use. However, I get the following error message when my application first loads:

Exception details:

System.Web.HttpException: Session state is not available in this context.

Source Error:

HttpSessionState session = new HttpApplication().Session;

My controller action is as follows:

public class RegistrationController : Controller
{
    // GET: Registration
    [HttpGet]
    public ActionResult Index()
    {
        HttpSessionState session = new HttpApplication().Session;

        CustomerStatusModel model = new CustomerStatusModel();
        model.CustomerStatusId = session["CustomerStatusId"];

        return View(model);
    }
}

I'm new to MVC 5 and also new to posting on StackOverflow. I could not find any similar posts. Any advice is much appreciated.

Upvotes: 3

Views: 4009

Answers (2)

davcs86
davcs86

Reputation: 3935

When you want to call Session and you're not working on an action, eg. an attribute, you can access with

HttpSessionState session = HttpContext.Current.Session;

Upvotes: 3

Nathan A
Nathan A

Reputation: 11339

You don't access Session by creating a new HttpApplication.

Just access Session directly, as it's a property of the Controller class.

public ActionResult Index()
{
    //DON'T DO THIS
    //HttpSessionState session = new HttpApplication().Session;

    CustomerStatusModel model = new CustomerStatusModel();

    //USE this.Session INSTEAD
    model.CustomerStatusId = Session["CustomerStatusId"]; 

    return View(model);
}

Upvotes: 1

Related Questions