0

我有根据用户 ID 和用户角色返回真或假的函数。

我有几个动作结果的控制器。

例如

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

     public ActionResult Contact(){}
  }

所以我想,每次当用户使用这个动作时,检查用户是否在角色中。

我知道我可以做到

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

但是这种方式,每次用户访问这个动作,都是一个额外的 SQL 查询。

我想在 MemCached 中存储用户角色,所以我的功能就像

 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;
 }

但是我怎样才能继承控制器中的所有动作来检查这个功能呢?

提示:也许覆盖 OnActionExecuting 或类似的?

4

1 回答 1

1

您可以编写一个RoleProvider从默认继承的自定义并覆盖GetRolesForUser方法:

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;
    }
}

显然,通过这样做,您完全承认如果某些外部进程修改了基本角色提供程序使用的数据存储中的角色,您可能会失去同步,因为现在您正在读取缓存的角色,而不是来自数据存储的角色。因此,在这种情况下,您可能需要放置一些同步机制来清除给定用户名的缓存数据。

于 2012-08-18T17:19:25.803 回答