c# - What is the Best Way to Create a Global Variable? -
i have simple question, important project: best way create global variable?
in project, when user authenticated, build web menus according profile, claims or roles (i create own claims), , start build menu, specifics pages wich user have permission access.
in filter method, check in database if user has permission access menu.
what wanna know if have possibility put list of menus in global variable, session ("/) or application, because dont wanna have go database check permissions, , in case better if list in server memory or that...
regards.
the best way handle situation child action. create action in controller in project. since deals user-level access, i'll use accountcontroller
.
[allowanonymous] [childactiononly] public actionresult usermenu() { if (user.identity.isauthenticated()) { // logic select menu database return view(menu); } // optionally can return different menu anonymous users here return content(""); }
then, create usermenu.cshtml
view in views\account
directory. in view, you'll use model instance passed in (menu
above) render portion of site navigation menu
object applies to.
finally, in layout, wherever want menu appear, call:
@html.action("usermenu", "account");
if want have run once (really better put "occasionally"), can utilize caching. add following additional attribute child action:
[outputcache(duration = 3600, varybycustom = "user")]
there's no built in way vary cache particular user, have create custom vary. it's relatively easy though. add following global.asax:
public override string getvarybycustomstring(httpcontext context, string arg) { if(arg.tolower() == "user") { if (context.user.identity.isauthenticated()) { return context.user.identity.name; } return null; } return base.getvarybycustomstring(context, arg); }
then, mvc cache output of usermenu
action each unique user 1 hour (3600 seconds), meaning other requests same user not invoke action or send queries database until cache has expired.
Comments
Post a Comment