【问题标题】:Asp.net MVC 3 CachingAsp.net MVC 3 缓存
【发布时间】:2012-04-19 23:31:52
【问题描述】:

我有一个对动作方法进行 ajax 调用的视图。

$.ajax({
url: url to action, 
type: 'GET',
cache: false,
dataType: 'html',
            success: function(result) {
                $("#divPatient").html(result);
                $("#divPatient").show("blind", { }, 2000);
                $("#loadingImage").hide();
                PrepPatientHtml();
            }
        });

如你所见,action 方法返回 html。该站点由 SQL 数据库驱动,该数据库在更改时会影响操作的输出。我添加了一个 NoCache 动作过滤器

public class NoCache : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();

            base.OnResultExecuting(filterContext);
        }
    }

由于某种原因,当支持视图的数据库发生更改时,缓存永远不会失效。有人有什么想法吗?视图相当简单:

@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "frm" }))
{
    <div style="padding: 10px;">
        <h1 id="questionsHeader">@Model.FullName (@Model.Dob)</h1>
        @for (var i = 0; i < Model.Episodes.Count; i++)
        {
            @Html.EditorFor(model => model.Episodes[i])
        }
    </div>
    <div style="padding-top: 10px; border-top: solid 1px #666666; margin-top: 5px; text-align: right;">
        <input type="submit" id="btnSaveAnswers" value="Save Answers" />        
    </div>
}

【问题讨论】:

    标签: asp.net-mvc-3 razor outputcache


    【解决方案1】:

    将此注释用于您的操作:

    [OutputCache(Duration = 0)]
    

    【讨论】:

    • 试过了……结果一样……好像实体框架正在为我缓存数据。
    【解决方案2】:

    我不相信它会是框架或你所说的“实体框架”(可能你想说点别的)。

    您是否调试过您的应用程序以查看操作是否实际被执行?

    如果是,您是否缓存了最终产生相同结果的对象?

    我的猜测是你的浏览器正在缓存结果。

    你试过了吗:

    response.setHeader( "Pragma", "no-cache" );
    response.setHeader( "Cache-Control", "no-cache" );
    response.setDateHeader( "Expires", 0 );
    

    如果不起作用,请尝试通过添加随机参数来更改 URL,例如:

    + '&uid=' + uniqueId()
    

    其中 uniqueId() 是一个函数,它可以及时为您获取一个唯一的字符串,例如 urlencoded 时间的刻度数。

    虽然最后一个选项可能不是最好的,但它肯定是最简单、最快的并且肯定会起作用。

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多