views:

39

answers:

2

Hi,

I'm using the asp.net membership provider for authentication of the user. I have another table with additional user details linked to my aspnet_users table.

When a user logs into my site I place what I call their 'UserProfile' into a session variable and I need to check the presence of this Session variable on every call in my controllers (all the controllers behind my login page).

So my question is this:

I've written an ActionFilter that inherits the AuthorizeAttribute which calls the default base.AuthorizeCore() method and checks for the presence of my Session object (Session["UserProfile"]), I've also created a base controller which holds my object of type UserProfile which all appropriate controller classes inherit from so they have access to my UserProfile. How do I use my method in my ActionFilter to set this UserProfile property to the Session variable in my controller?

A: 

Why can't you simply do that in the base controller? That seems like the right place to populate the property. Doing in your custom authorize attribute will create a dependency that needn't exist and lead to more complexity. What I'm saying is the check for the presence of the key in the Session, while related, isn't the same as populating the property. It could, in fact, be very different if you eventually decided, for instance, to store only a DB key in the session and retrieve a more complex profile object from the DB each time. Note also that the authorize attribute could later be applied to simply a method instead of a class -- at that point, you might be performing the population of the property multiple times.

If you feel that you must, however, the AuthorizationContext passed to the OnAuthorization method of the attribute contains a reference to the controller. You could cast this as your base controller (using as syntax and checking for nullity), then access the property directly (if public) or via reflection (if not).

tvanfosson
A: 

Same as tvanfosson, don't add a property to your controller base, that depends on an ActionFilter being applied.

An alternative is moving the code to a separate class that retrieves/checks access to the said property. Both the ActionFilter and the controller base use said class to retrieve the value. The dependency is made explicitly, which makes it a Lot easier to understand for another developer.

eglasius