tags:

views:

63

answers:

3

In my asp.net mvc project I store two objects in the session when the user logs in. One is a User object (representing the logged in user) and the other is the Organisation object (representing the user's organisation).

I need one or both of these objects to be available in every action method. What's the most elegant way of dealing with this? At the moment each action takes parameters for each of these objects, with a custom model binder retrieving the objects from session. This at least encapsulates the session access but it's annoying to have the params in every method signature. Is there a better way?

Here's what most of the action methods look like.

    public ActionResult Pending(IUser CurrentUser)
    {
        var users = CurrentUser.GetMyOrgPendingUsers();
        return View(users);
    }
A: 

The Controller class has a User property. Have you considered using this rather than designing your own way to track the current user?

ctford
I did look into that, but it seemed necessary to implement IPrincipal in that scenario, and I'm building on top of an existing class library.
Central Scrutinizer
A: 

I'd rethink using IPrincipal here--it is very handy and allows you to work your way into the rest of the .NET authentication bits very seamlessly.

As for the problem at hand, perhaps the easiest clean course of action would be to wire them into a base controller class as protected properties. Slightly more elegant would be to create a user context class, that takes a reference to Session (or better yet, whatever base interfaces you are using in the session) and expose that class from the controller. The main advantage there is it makes it easier to change the backing store if need be and lets one encapsulate more behavior in general.

Wyatt Barnett
+1  A: 

Since you need to access IUser in almost every action you can have a base controller from where every other controller is derived. In the base controller put IUser as a member variable and override the OnActionExecuting() method in the base controller, in which you can put the code to access the session variables.

OnActionExecuting() will be called every time a action is called.

San