views:

174

answers:

3

Hi everyone

I'm only a newcomer to ASP.NET MVC and am not sure how to achieve a certain task the "right way".

Essentially, I store the logged in userId in HttpContext.User.Identity and have written an EnhancedAuthorizeAttribute to perform some custom authorization.

In the overriden OnAuthorization method, my domain model hits the database to ensure the current user id can access the passed in routeValue "BatchCode". The prototype is:

ReviewGroup GetReviewGroupFromBatchCode(string batchCode);

It will return null if the user can't access the ReviewGroup and the OnAuthorization then denies access.

Now, I know the decorated action method will only get executed if OnAuthorization passes, but I don't want to hit the database a second time to get the ReviewGroup again.

I am thinking of storing the ReviewGroup in HttpContext.Items["reviewGroup"] and accessing this from the controller at the moment.

Is this a feasible solution, or am I on the wrong path?

Thanks!

A: 
Raj Kaimal
Well no, I don't need the ReviewGroup object for more than a single request. Really, all I need is to pass this object (obtained in the AuthorizeAttribute.OnAuthorization()) to the ActionMethod().
A: 

Unless your doing a VERY big select from ReviewGroup or you have a enormous database, then a second database hit wouldn't be too much of an issue. Modern databases are very efficient at making selects, especially with properly indexed tables.

In my experience, this is the best way of doing authorisation and a similar method to how I authorized specific actions in my applications.

So in short, I wouldn't worry at all about the second database hit.

Alastair Pitts
+1  A: 

Alternatively, one of the best ways to avoid hitting the database, and easiest, is caching. Retrieve it, stick it in a cache. If it it's needed again it's already in memory and no DB hit is required. If not, then when the cache goes out of scope, so will the object.

krisg