Thuan
Thuan

Reputation: 1628

Response.End() causes session lost the first time session is used

I have a site built using MVC 2. My problem is that Response.End() causes session lost the first time session is accessed.

Test case 1:

  1. Start the application.

  2. Go to Home/X. An item is added to session and Response.End() is called.

  3. Open Home/X again and check Session["X"] (add a break point before the assignation line.) It returns null. Execute the rest of the action which assign "X" to session again.

  4. Reopen Home/X. This time Session["X"] returns correct value.

Test case 2:

  1. Keep the web application running. Close the browser and reopen to open a new session. Visit Home/X.

  2. Result: Session["X"] always has a value.

Could anyone please explain to me why this happens and how to solve it?

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }
    public void X()
    {
        Session["X"] = "X";
        Response.End();
    }
}

Upvotes: 2

Views: 973

Answers (1)

Thuan
Thuan

Reputation: 1628

Adding

    public void Session_OnStart()
    {
    }

to Global.asax helps fix the problem.

Upvotes: 1

Related Questions