Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC AuthorizeAttribute passing values to ActionMethod?

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!

like image 268
Adam Mikulasev Avatar asked May 14 '10 01:05

Adam Mikulasev


People also ask

How to pass parameters to ASP action?

There are a number of ways in which you can pass parameters to action methods in ASP.NET Core MVC. You can pass them via a URL, a query string, a request header, a request body, or even a form. This article talks about all of these ways, and illustrates them with code examples.

What is ASP Net mvc6?

ASP.NET MVC is a web application framework developed by Microsoft that implements the model–view–controller (MVC) pattern. It is no longer in active development. It is open-source software, apart from the ASP.NET Web Forms component, which is proprietary. ASP.NET MVC. Developer(s)


2 Answers

The HttpContext.Items is alive only for the duration of the request. If you want to persist it for a longer time, you should put it in

a) session - good

b) profile - dont see the advantage

c) cookie - not recommended

d) hit the database everytime - should be OK

Store it in filterContext.RouteData.DataTokens?

like image 69
Raj Kaimal Avatar answered Oct 11 '22 13:10

Raj Kaimal


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.

like image 30
krisg Avatar answered Oct 11 '22 12:10

krisg