简体   繁体   中英

Create class to return Session User Information

Hello :) I am building an MVC5/EF6 system that has stores information about students with a number of user types . When the user logs in certain information about the user is stored in Session; UserID, UserTypeID etc. Different users have different privileges, and I often need to get the user information from Session within my ActionResult methods in each controller:

private Student GetCurrentStudentInfo()
{
    var currentuser = (SessionModel)Session["LoggedInUser"];
    var student = _db.Student.Find(currentuser.UserID);
    return student;
}

I have this method at the bottom of my controllers, which I call from each method depending on when I need this information. It gets the userID from the current logged in user and returns the profile information. I would like to be able to either:

  1. Make this method available to all my controllers
  2. Or create a class variable that I can use at the top of my controller, which would return this info:

     public class RegistrationWizardController : Controller { private readonly DefaultContext _db = new DefaultContext(); private UserInfo _userInfo = new UserInfo(); } 

I am very new to MVC and coding in general, so any help/opinions/other suggestions are welcome. Thanks!

You have a couple of options.

The first (and easier) of the two is to make all of your controllers inherit from a common base controller. To do this, make a base controller that extends from the default controller:

public class BaseController : Controller
{
    protected Student GetCurrentStudentInfo() //protected so we can access this method from derived classes
    {
        var currentuser = (SessionModel)Session["LoggedInUser"];
        var student = _db.Student.Find(currentuser.UserID);

        return student;
    }
}

Now, change your controllers to inherit the base controller you just created:

public class RegistrationWizardController : BaseController
{
    public ActionResult AnAction()
    {
        var student = this.GetCurrentStudentInfo(); //calls the method inherited from BaseController
    }
}

The other option you have is to use Dependency Injection. This is a bit more complicated, and much more abstract than the previous method. There are a bunch of Dependency Injection frameworks, my favorite is Ninject ( http://www.ninject.org/ ). This would probably be closer to the "Industry Standard" of doing something like this, and I would encourage you to at least look into it, but I think a sample would be a little out of scope for this question (do some side reading first). If you do decide to implement it and get stuck, post another question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM