Bill Software Engineer
Bill Software Engineer

Reputation: 7822

Where should I save User data in the MVC paradigm so it's accessible at all levels?

Background:

I am new to MVC and is just learning how to do things.

What I am trying to do:

I am trying to make User data available for all actions.

How I am achieving it:

I achieve this by loading User data in the OnActionExecuting function.

The problem I ran into:

I don't know where to store my User data and how to retrieve it at a later time (ie, during the action).

Current Code:

Here I am loading the current User.

    protected override void OnActionExecuting(ActionExecutingContext ctx) {
        base.OnActionExecuting(ctx);
        UserAccount user = null;
        using (UsersContext db = new UsersContext()) {
            user = db.UserProfiles.FirstOrDefault(u => u.userName.ToLower() == User.Identity.Name.ToLower());
        }
    }

How do I get it in these places?

    public ActionResult Default() {
        ViewBag.Message = user.userName;  // ????????????
        return View();
    }

Possible Solution:

  1. Just save it in a parameter.
  2. User HttpContext (Not sure how this will work, please help).
  3. User ControllerContext (Not sure how this will work, please help).
  4. ViewState?
  5. ViewBag?
  6. Cache?
  7. Any other type of MVC magic

Upvotes: 2

Views: 3829

Answers (1)

Mihail Shishkov
Mihail Shishkov

Reputation: 15887

Just make your controllers inherit some base controller class like that

public class AccountController : BaseController

then in the BaseController you are free to create methods or proerties that represent the User's data and they will be available in all actions of the AccountController.

public class BaseController : Controller
{
      public User CurrentUser
        {
            get
            {
                if (HttpContext.User == null || HttpContext.User.Identity.AuthenticationType != "Forms")
                    return null;
                if (Session["CurrentUser"] != null)
                    return (User)Session["CurrentUser"];
                var identity = HttpContext.User.Identity;
                var ticket = ((FormsIdentity)identity).Ticket;
                int userId;
                if (!int.TryParse(ticket.UserData, out userId)
                    return null;

                using (var db= new DbEntities(connectionString))
                {
                    Session["CurrentUser"] = db.Users.SingleOrDefault(u => u.ID == userId));
                }

                return (User)Session["CurrentUser"];
            }

        set { Session["CurrentUser"] = value; }
        }
}

Upvotes: 3

Related Questions