0

I have function which return true or false depend of UserID and User Role.

I have controller with several action results.

for example

  public class DemoController : Controller
  {
     public ActionResult Index(){}

     public ActionResult Contact(){}
  }

So i want , everytime when user use this actions, to check if user is in role.

I know i can make it like

[Authorize(Roles = "Administrator")]
public ActionResult JustAdmins(){}

But this kind of way, everytime user visit this action, its an extra SQL Query.

My want to store user role in MemCached so my function will be like

 public static bool IsCompany(Guid UserID)
 {

    //if (get from cache != null && get from cache == "Role")
    // return true
    //if (get from DB != null && get from DB == "Role")
    //return true

    return false;
 }

But how i can inherit all Action in my controller to check this function ?

tip: maybe override OnActionExecuting or similar ?

Novkovski Stevo Bato
  • 1,013
  • 1
  • 23
  • 56

1 Answers1

1

You could write a custom RoleProvider inheriting from the default one and override the GetRolesForUser method:

public class CachingRoleProvider: THE_ROLE_PROVIDER_YOU_ARE_CURRENTLY_USING
{
    public override string[] GetRolesForUser(string username)
    {
        string[] roles;
        if (TryCheckFromYourCacheIfUserIsInRole(username, out roles))
        {
            // the roles for this user were retrieved from the cache
            return roles;
        }

        // no roles retrieved from the cached => query the base role provider
        roles = base.GetRolesForUser(username);

        // Store the retrieved roles into the cache so that on subsequent calls
        // you no longer need hit the base role provider for this user
        PutRoleInCacheForUser(username, roles);

        return roles;
    }
}

Obviously by doing this you completely acknowledge the fact that you could get out of sync if some external process modifies the roles in the datastore used by your base role provider since now you are reading the cached roles, not the ones from your datastore. So you might need to put some synchronization mechanisms in order to evict the cached data for the given username in this case.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928