2

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; }
    }
}
}
Community
  • 1
  • 1
Juan Pablo Gomez
  • 5,203
  • 11
  • 55
  • 101
  • SessionBag is an object to manage session vars. i'm posting that code – Juan Pablo Gomez Oct 28 '12 at 16:35
  • 2
    Why are you storing the UserName in session which can be disposed of at any time without your knowledge? Once you set the FormsAuthenticationTicket, you can get the username from the HttpContext.Identity.User.Name call – Tommy Oct 28 '12 at 16:49
  • UserName are only one of many session vars that my app manage .. all other are lost to. – Juan Pablo Gomez Oct 28 '12 at 16:50
  • Very tks for your help'm trying to use HttpContext.Identity.User.Name at one of my cntroller, but it showme HttpContextBase doesn't have a definition for Identity. – Juan Pablo Gomez Oct 28 '12 at 17:00

2 Answers2

1

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..

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Very tks for your help. But i'm little confused about set Sesssion["test"]= DateTime.Now, it means change my sessionid to datetimeNow or to create a test var in sessionbag ? tks. – Juan Pablo Gomez Oct 28 '12 at 17:05
  • I'm set **Test** Session["Test"] = DateTime.Now; as you ask me. but it is lost too when try to accesit in other controllers. – Juan Pablo Gomez Oct 28 '12 at 17:20
  • On the same request or future requests or both? Does the session I'd come over in the headers? Use glimpse to debug and view headers or use fiddler – Adam Tuliper Oct 28 '12 at 18:07
  • You are right, my session is restarting over and over again, this development machine is new.. think something configuration are bad. the last exception throwed after session restart is: External component has throw an exception (System.Runtime.InteropServices.SEHException) Do you have any Idea? tks for your patience. – Juan Pablo Gomez Oct 28 '12 at 18:38
  • Is your browser sendin over the same session Id or is a new one issued at that point and sent down in a set-cookie header? – Adam Tuliper Oct 29 '12 at 02:43
  • Very tks for your interest on help me. Finally found the problem. Recently our MVC3 app was migrated to MVC4, and some keys on original web.config are diferent. Just Updates web.config, added and removed some keys and everithing is working fine. TKS – Juan Pablo Gomez Oct 29 '12 at 20:42
  • any idea which keys were causing the issue? – Adam Tuliper Oct 30 '12 at 20:14
  • Exactly? Not just take a clean MVC4 web.config and add some keys that I need but already have boot versions if you are interested on see it. – Juan Pablo Gomez Oct 30 '12 at 22:24
  • just want to make sure anyone else here has a resolution when they see this posting – Adam Tuliper Oct 31 '12 at 04:58
1

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.

Juan Pablo Gomez
  • 5,203
  • 11
  • 55
  • 101