Asp.net mvc 3 NET MVC3,如何将不同的OutputCacheProfile用于不同的用户角色?
我知道我可以在web.config文件中设置OutputCacheProfilesAsp.net mvc 3 NET MVC3,如何将不同的OutputCacheProfile用于不同的用户角色?,asp.net-mvc-3,web-config,browser-cache,outputcache,user-roles,Asp.net Mvc 3,Web Config,Browser Cache,Outputcache,User Roles,我知道我可以在web.config文件中设置OutputCacheProfiles 我想知道如何将不同的缓存配置文件应用到页面(控制器)级别上的不同的用户角色。您可以使用OutputCache属性装饰控制器,该属性允许参数作为参数传递。比如, [OutputCache(Duration = 3600, VaryByParam = "None")] 没有理由不能扩展该属性以获取进一步的参数“RoleName”并执行“Roles.IsUserInRole(RoleName)”并根据每个角色加载不同
我想知道如何将不同的缓存配置文件应用到页面(控制器)级别上的不同的用户角色。您可以使用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>
以下是完整的Index.cshtml文件
@model DateTime
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
The time is @Model.TimeOfDay.ToString()
</p>
下一行允许您在控制器内设置配置文件
public ActionResult Index()
{
// Forces the cache profile to one of the name of "Mandatory".
HttpContext.Items["Cache.Force"] = "Mandatory";
return View(IndexViewName, DateTime.Now);
}
如果我能提供进一步帮助,请告诉我
马特谢谢。看起来任何接受临时值的地方都可以用于此方法。取景袋怎么样?我现在将尝试这个方法,不得不说,将方法从OnActionExecuting更改为OnActionExecuted是一个明智之举。嗨,Matt,测试后。Change CacheProfile@OnActionExecuting正在运行,但@OnActionExecuted未运行。CacheProfile的值已更改,但缓存结果未更改。可能缓存已在OnActionExecution之后但在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);
}