Mohammad hossein
Mohammad hossein

Reputation: 255

get current session in mvc3 controller

i define session["username]" in Login.cs when user want to login

    public static void SetLogin(string username, bool remmember)
        {
             HttpContext.Current.Session["username"] = username;
        }

and i want use value of session["username"] in UserPanelController

    public class UserPanelController : Controller
    {
        Customer cu;
        Customer.customer cust;
        public UserPanelController()
        {
            if (Login.ChekLogin())
            {
                cust = cu.Read(int.Parse(Session["username"].ToString()));
                // error Occur here Session is null
            }

        }
    }

i can't access to session because is null

Upvotes: 0

Views: 5320

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039150

You seem to be attempting to use the Session in the constructor of an ASP.NET MVC controller. It's normal that it is null. The session is initialized at a later stage - in the Initialize method:

public class UserPanelController : Controller
{
    Customer cu;
    Customer.customer cust;

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        if (Login.ChekLogin())
        {
            cust = cu.Read(int.Parse(Session["username"].ToString()));
            // error Occur here Session is null
        }
    }
}

Also you seem to be attempting to cast the username to an integer. Are you sure that this is the case?

Also why are you using a Session for something that's already handled for you by the FormsAuthentication?

Upvotes: 5

Related Questions