开发者

How can I read the properties of an object that I assign to the Session in ASP.NET MVC?

I'm trying my hand at creating a session which stores member information which the application can use to reveal certain navigation and allow access to certain pages and member role specific functionality.

I've been able to assign my MemberLoggedIn object to the session in this way:

    //code excerpt start...

    MemberLoggedIn loggedIn = new MemberLoggedIn();

    if (computedHash == member.Hash)
    {
        loggedIn.ID = member.ID;
        loggedIn.Username = member.Username;
        loggedIn.Email = member.Email;
        loggedIn.Superuser = member.Superuser;
        loggedIn.Active = member.Active;

        Session["loggedIn"] = loggedIn;
    }
    else if (ModelState.IsValid) {
        ModelState.AddModelError("Password", "Incorrect Username or Password."); 
    }

    return View();

That works great. I then can send the properties of Session["loggedIn"] to the View in this way:

    [ChildActionOnly]
    public ActionResult Login(开发者_如何学Go)
    {
        if (Session["loggedIn"] != null)
            ViewData.Model = Session["loggedIn"];
        else
            ViewData.Model = null;
        return PartialView();
    }

In the Partial View I can reference the session data by using Model.Username or Model.Superuser.

However, it doesn't seem to work that way in the controller or in a custom Action Filter. Is there a way to get the equivalent of Session["loggedIn"].Username?


Remember that ASP.Net MVC uses wrappers around the static ASP.Net singletons like Application and Session. This is to allow code to be decoupled from, and unit tested outside of the ASP.Net pipeline.

From an action filter, use:

((MembershipUser)filterContext.HttpContext.Session["loggedIn"]).Username 

And from inside a controller, use:

((MembershipUser)ControllerContext.HttpContext.Session["loggedIn"]).Username


Like this:

MemberLoggedIn user = (MemberLoggedIn)HttpContext.Session["loggedIn"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜