Question

I have an MVC 3 application, it use asp validation when the user logs in the app the validadion succeed and sotore user name in a session variable.

At here everithing works fine.

then in the AccountController i Set a RedirectionToAction, to another controller, here the session variables are lost.

**//HERE THE VARIABLES ARE LOST AND AN ERROR HAPPENS**
return RedirectToAction("menuOtbr", "Menu", new { area = "Configuracion" });

I've tryed

  1. Change from InProc to ServerState and problem persists,
  2. Deactivate my AV.
  3. Adding protected void Session_Start(){} nothing happens. the session doesn't start or restart again.

  4. Other many suggestions almost all articles published with this related topic was readed an applyed by me.

here is my code:

        [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            //  Se inicializa variables para el gestor de mensajes 
            SessionBag.Current.ErrorMessageAuto = new ArrayList();
            SessionBag.Current.ErrorMessage = null;
            SessionBag.Current.ErrorReturnTo = null;

            //Se verifica si el usuario es válido en el contexto de SQL Server, esto para guardar 
             //compatibilidad con el diseño de Merlin para Escritorio.
            Db_Conexion db = new Db_Conexion(model.UserName,model.Password);
            if (!db.connect())
            {
                model.UserName = null;
                model.Password = null;
                SessionBag.Current.ErrorReturnTo = "link";
                SessionBag.Current.ErrorMessage = db.ExceptionsText();
                return View("Mensajes");
            }
            db.close();

            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                SessionBag.Current.UserName = model.UserName;

                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    **//HERE THE VARIABLES ARE LOST AND AN ERROR HAPPENS**
                    return RedirectToAction("menuOtbr", "Menu", new { area = "Configuracion" });
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

I have the account controller at root's project and another controllers structured by areas.

Project Structure

Almost 10 days spent trying to solve this. Any Ideas, help would be very apreciated.

The same error happens boot at deployment or production.

This article Losing my session variables - What exception might cause sessions to be lost?

say about some IIS configuration. But doesn't explain exactly what things need to be configured.

SessionBags Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Dynamic;

namespace ParadigmaNet.Infraestructure
{
public sealed class SessionBag : DynamicObject
{
    private static readonly SessionBag sessionBag;

    static SessionBag()
    {
        sessionBag = new SessionBag();
    }

    private SessionBag()
    {
    }

    private HttpSessionStateBase Session
    {
        get { return new HttpSessionStateWrapper(HttpContext.Current.Session); }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = Session[binder.Name];
        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        Session[binder.Name] = value;
        return true;
    }

    public override bool TryGetIndex(GetIndexBinder
           binder, object[] indexes, out object result)
    {
        int index = (int)indexes[0];
        result = Session[index];
        return result != null;
    }

    public override bool TrySetIndex(SetIndexBinder binder,
           object[] indexes, object value)
    {
        int index = (int)indexes[0];
        Session[index] = value;
        return true;
    }

    public static dynamic Current
    {
        get { return sessionBag; }
    }
}
}
Was it helpful?

Solution 2

After days and hours of tests, Found some problems on web.config.

Recently we change our app from MVC3 to MVC4, and find some diferences between web.config on boot strucutres, we made some changes, drop some keys and add others.

After that everything is working ok.

We generate a clean MVC4 app then compare web.config with the old web.config and procceed to remove some keys and modify anothers.

OTHER TIPS

Rather than trying to debug session bag how about simplifying this. When a user logs in simply set Sesssion["test"]= DateTime.Now

Then write it out directly from each controller.

If a new session doesn't start I don't believe your session is getting lost and tend to think its an implementation issue.

Is your session id sent over in each request when you think it's lost? I'm going to guess it is, hence why you don't see a new session getting created.

If the test above works then you know it's a sessionbag implementation issue..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top