【问题标题】:Partial caching of custom WebControls自定义 WebControl 的部分缓存
【发布时间】:2012-03-27 13:26:11
【问题描述】:

我需要缓存自定义 WebControls 的生成内容。由于控制集合层次结构的构建非常昂贵,因此数据库结果的简单缓存是不够的。缓存整个页面是不可行的,因为页面内部还有其他动态部分。

我的问题:是否有解决此问题的最佳实践方法?我发现很多缓存整个页面或静态用户控件的解决方案,但没有适合我的。我最终得到了自己的解决方案,但我很怀疑这是否可行。

应缓存的自定义 WebControl 可能如下所示:

public class ReportControl : WebControl
{
    public string ReportViewModel { get; set; }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // Fake expensive control hierarchy build up
        System.Threading.Thread.Sleep(10000);

        this.Controls.Add(new LiteralControl(ReportViewModel));
    }
}

包含内容控件的 aspx 页面可能如下所示:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Fake authenticated UserID
        int userID = 1;

        // Parse ReportID
        int reportID = int.Parse(Request.QueryString["ReportID"]);

        // Validate if current user is allowed to view report
        if (!UserCanAccessReport(userID, reportID))
        {
            form1.Controls.Add(new LiteralControl("You're not allowed to view this report."));
            return;
        }

        // Get ReportContent from Repository
        string reportContent = GetReport(reportID);

        // This controls needs to be cached
        form1.Controls.Add(new ReportControl() { ReportViewModel = reportContent });
    }

    private bool UserCanAccessReport(int userID, int reportID)
    {
        return true;
    }

    protected string GetReport(int reportID)
    {
        return "This is Report #" + reportID;
    }
}

我最终编写了两个包装器控件,一个用于捕获生成的 html,另一个用于缓存内容 - 用于简单缓存功能的代码非常多(见下文)。

用于捕获输出的包装器控件会覆盖函数 Render,如下所示:

public class CaptureOutputControlWrapper : Control
{
    public event EventHandler OutputGenerated = (sender, e) => { };

    public string CapturedOutput { get; set; }

    public Control ControlToWrap { get; set; }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        this.Controls.Add(ControlToWrap);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

        base.RenderChildren(htmlTextWriter);

        CapturedOutput = stringWriter.ToString();

        OutputGenerated(this, EventArgs.Empty);

        writer.Write(CapturedOutput);
    }
}

用于缓存此生成的输出的包装控件如下所示:

public class CachingControlWrapper : WebControl
{
    public CreateControlDelegate CreateControl;

    public string CachingKey { get; set; }

    public delegate Control CreateControlDelegate();

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        string content = HttpRuntime.Cache.Get(CachingKey) as string;

        if (content != null)
        {
            // Content is cached, display
            this.Controls.Add(new LiteralControl(content));
        }
        else
        {
            // Content is not cached, create specified content control and store output in cache
            CaptureOutputControlWrapper wrapper = new CaptureOutputControlWrapper();
            wrapper.ControlToWrap = CreateControl();
            wrapper.OutputGenerated += new EventHandler(WrapperOutputGenerated);

            this.Controls.Add(wrapper);
        }
    }

    protected void WrapperOutputGenerated(object sender, EventArgs e)
    {
        CaptureOutputControlWrapper wrapper = (CaptureOutputControlWrapper)sender;

        HttpRuntime.Cache.Insert(CachingKey, wrapper.CapturedOutput);
    }
}

在我的 aspx 页面中我替换了

// This controls needs to be cached
form1.Controls.Add(new ReportControl() { ReportViewModel = reportContent });

CachingControlWrapper cachingControlWrapper = new CachingControlWrapper();
// CachingKey - Each Report must be cached independently
cachingControlWrapper.CachingKey = "ReportControl_" + reportID;
// Create Control Delegate - Control to cache, generated only if control does not exist in cache
cachingControlWrapper.CreateControl = () => { return new ReportControl() { ReportViewModel = reportContent }; };

form1.Controls.Add(cachingControlWrapper);

【问题讨论】:

  • 设置页面指令。 <%@ OutputCache Duration="30000" VaryByParam="ReportID" %> 根据reportID 或<%@ OutputCache Duration="30000" VaryByParam="*" %> 用于所有查询字符串参数
  • 我无法缓存整个页面,如上所述。

标签: asp.net caching web-controls


【解决方案1】:

似乎是个好主意,也许你应该注意:

  • 自定义控件的子控件的 ClientIdMode 以防止在其他上下文中显示这些控件时发生冲突
  • Literal 的 LiteralMode:应该是 PassThrough
  • 缓存项的过期模式(absoluteExpiration/slidingExpiration)
  • 禁用 CustomControl 的 ViewState

最近,我倾向于采用另一种方法:我的包装器控件仅包含一些在仅包含我的自定义控件的页面上执行 AJAX GET 请求的 javascript。 客户端通过 http 标头执行缓存,服务器端通过 OutputCache 指令执行缓存(除非 HTTPS,但内容必须是公开的)

【讨论】:

  • 好话 - 我会考虑的。因此,您为每个控件制作一个页面进行缓存 - 页面内容由客户端通过 JS 调用?
  • 是的,在正确的上下文中使用,它有助于在应用程序、服务器和第三方站点之间共享控件(例如导航控件)。这减少了带宽和服务器开销。
  • 听起来很符合您的要求。对于我的特殊情况,似乎有点间接。我必须在服务器端进行调用,并且无法从客户端直接访问带有缓存控件的页面。如果我的 UserCanAccessReport 为真,我会拨打电话并可以使用返回的内容制作 LiteralControl。不过感谢您的意见。
猜你喜欢
  • 2011-01-17
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多