ASP.NET MVC session lost between page loads

2019-07-29 07:15发布

问题:

I am trying to use session state in MVC and I have been stuck for the entire evening! I realise session state should be used sparingly in MVC - but I am sure I want to use it for this one page - so would appreciate solutions rather than opinions.

Basically, I have a contact form with a CAPTCHA image. When the page loads I want to set the session to the characters used in the CAPTCH image (dynamically generated image). I have an 'new image' link which async creates a new code, sets the session and dynamically loads a new image to screen.

The session stays sets as long as the page doesn't load or reload. I need to be able to validate the user input against the code in session (which should reflect what is displayed to the user) but the session is empty.

If I perform an AJAX reload on the image i.e. set the session asynchronously - the session is set when I perform a post!!

What's going on?

I need to be able to persist the session value - arrrhhhh!

I have this is a base controller:

public new HttpContextBase HttpContext
{
   get
   {
      HttpContextWrapper context = new HttpContextWrapper(System.Web.HttpContext.Current);
      return (HttpContextBase)context;
   }
 } 

and in the controller I have:

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Contact(ContactForm c, string button)
  {
    string sessCaptcha = HttpContext.Session["CAPTCHA_Contact"] == null ? "" : HttpContext.Session["CAPTCHA_Contact"].ToString();
  }

Any ideas????? pretty pls with a cherry on top :)

Thanks!

回答1:

I am so embarrased right now...

Never ever set a session value before a Response.End() (and i believe also the same applies to response.redirect).

OMG - that's 4 hours I will never ever get back again!

Here is the demo code to illustrate my ineptitude...

   public ActionResult Page1()
        {
            Session["test1"] = "hello world";

            // This means the session won't be set
            // It's is used in valid circumstances..e.g. setting session, then dynamically generating an image based on that value.
            Response.End();

            return View();
        }

        public ActionResult Page2()
        {
            ViewBag.Test = Session["test1"].ToString();

            return View();
        }

        [HttpPost]
        public ActionResult Page2(FormCollection fc)
        {
            ViewBag.Test = "...is still..." + Session["test1"].ToString();

            return View();
        }


回答2:

You may want to look into using the TempData object

http://blog.donnfelker.com/2010/02/26/aspnet-mvc2-tempdata-now-persists/