Reputation: 7822
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:
Upvotes: 2
Views: 3829
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