ASP.NET MVC3,如何对不同的用户角色使用不同的OutputCacheProfile?

发布于 2024-12-17 10:36:39 字数 149 浏览 0 评论 0原文

我知道我可以在 web.config 文件中设置 OutputCacheProfiles。

我想知道如何在页面(控制器)级别将不同的缓存配置文件应用到不同的用户角色

I know I can setup OutputCacheProfiles at web.config file.

I like to know how to apply different cache profile to different user role on page (controller) level?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意犹 2024-12-24 10:36:39

您可以使用 OutputCache 属性来装饰控制器,该属性允许将参数作为参数传递。例如;

[OutputCache(Duration = 3600, VaryByParam = "None")]

您没有理由无法扩展该属性以采用进一步的参数“RoleName”并执行“Roles.IsUserInRole(RoleName)”并根据每个角色加载不同的设置。

编辑

经过作者的评论,我审查了我的解决方案。

首先,您可以在 Web.config 中定义缓存配置文件;

<caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <clear />

      <add name="Default" duration="60" />
      <add name="Admin" duration="10" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>

我已经扩展了 OutputCacheAttribute 来考虑用户的授权,如果用户进行了身份验证,它就会加载 CacheProfile;

public class AuthorisedOutputCache : OutputCacheAttribute
{
  public string RoleName { get; set; }

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    // Default Profile.
    CacheProfile = "Default";

    if (HttpContext.Current.Request.IsAuthenticated)
    {
      if (Roles.IsUserInRole(RoleName))
      {
        CacheProfile = RoleName;
      }
    }

    base.OnActionExecuting(filterContext);
  }
}

为了完整起见,这里是 Index.cshtml 文件;

@model DateTime

@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
  The time is @Model.TimeOfDay.ToString()
</p>

注意:您必须确保为每个角色定义一个缓存配置文件,以及未找到角色时的默认配置文件。

编辑

作者希望知道如何在控制器内设置缓存配置文件,我已经发布了一个可行的解决方案,但我不喜欢它,因为使用了 HttpContext.Items - 所以是否有人可以建议替代方案?

首先,必须将OnActionExecuting更改为OnActionExecuted;

public class AuthorisedOutputCache : OutputCacheAttribute
{
  public string RoleName { get; set; }

  public override void OnActionExecuted(ActionExecutedContext filterContext)
  {
    // Do you wish to force the profile?
    if (HttpContext.Current.Items["Cache.Force"] != null)
    {
      // Force the profile and remove the flag.
      CacheProfile = HttpContext.Current.Items["Cache.Force"].ToString();
      HttpContext.Current.Items.Remove("Cache.Force");
    }
    else
    {
      // If the profile has not been set - use the role based authorisation - 
      // otherwise, carry on as normal.
      if (string.IsNullOrEmpty(CacheProfile))
      {
        CacheProfile = "Default";

        if (HttpContext.Current.Request.IsAuthenticated)
        {
          if (Roles.IsUserInRole(RoleName))
          {
            CacheProfile = "Admin";
          }
        }
      }
    }

    base.OnActionExecuted(filterContext);
  }
} 

以下行允许您在控制器内设置配置文件;

public ActionResult Index()
{
  // Forces the cache profile to one of the name of "Mandatory".
  HttpContext.Items["Cache.Force"] = "Mandatory";

  return View(IndexViewName, DateTime.Now);
}

如果我可以提供进一步的帮助,请告诉我,

马特

You can decorate a controller with the OutputCache attribute which allows arguments to be passed as parameters. For example;

[OutputCache(Duration = 3600, VaryByParam = "None")]

There is no reason why you couldn't extend the attribute to take a further argument "RoleName" and perform a "Roles.IsUserInRole(RoleName)" and load different settings based upon each role.

EDIT

After comments from the author, I have reviewed my solution.

Firstly, you can define you cache profiles within the Web.config;

<caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <clear />

      <add name="Default" duration="60" />
      <add name="Admin" duration="10" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>

I have extended the OutputCacheAttribute to account for authorisation of a user, and if the user authenticates, it loads that CacheProfile;

public class AuthorisedOutputCache : OutputCacheAttribute
{
  public string RoleName { get; set; }

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    // Default Profile.
    CacheProfile = "Default";

    if (HttpContext.Current.Request.IsAuthenticated)
    {
      if (Roles.IsUserInRole(RoleName))
      {
        CacheProfile = RoleName;
      }
    }

    base.OnActionExecuting(filterContext);
  }
}

Here is the Index.cshtml file for completeness;

@model DateTime

@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
  The time is @Model.TimeOfDay.ToString()
</p>

Note: You will have to make sure to define a cacheprofile for each of your roles, aswell as a default for when no role is found.

EDIT

The author wished to know how to set the cache profile within the controller, I have posted a viable solution, but I don't like it because of the use of HttpContext.Items - so if anyone can suggest alternatives?

Firstly, you must change the OnActionExecuting to OnActionExecuted;

public class AuthorisedOutputCache : OutputCacheAttribute
{
  public string RoleName { get; set; }

  public override void OnActionExecuted(ActionExecutedContext filterContext)
  {
    // Do you wish to force the profile?
    if (HttpContext.Current.Items["Cache.Force"] != null)
    {
      // Force the profile and remove the flag.
      CacheProfile = HttpContext.Current.Items["Cache.Force"].ToString();
      HttpContext.Current.Items.Remove("Cache.Force");
    }
    else
    {
      // If the profile has not been set - use the role based authorisation - 
      // otherwise, carry on as normal.
      if (string.IsNullOrEmpty(CacheProfile))
      {
        CacheProfile = "Default";

        if (HttpContext.Current.Request.IsAuthenticated)
        {
          if (Roles.IsUserInRole(RoleName))
          {
            CacheProfile = "Admin";
          }
        }
      }
    }

    base.OnActionExecuted(filterContext);
  }
} 

The following line allows you to set the profile within the controller;

public ActionResult Index()
{
  // Forces the cache profile to one of the name of "Mandatory".
  HttpContext.Items["Cache.Force"] = "Mandatory";

  return View(IndexViewName, DateTime.Now);
}

Let me know if I can be of further assistance,

Matt

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文