不缓存[ChildActionOnly]操作在ASP.NET MVC中不起作用

时间:2015-03-12 02:52:33

标签: c# asp.net asp.net-mvc asp.net-mvc-4 outputcache

在我的ASP.NET MVC应用中,我有一个MenuController,其中Index方法用[ChildActionOnly]修饰:

public class MenuController : Controller
{
    [OutputCache(Location=OutputCacheLocation.None, Duration=0, NoStore=true)]
    [ChildActionOnly]
    public PartialViewResult Index()
    {
        return PartialView();
    }
}

Index.cshtml部分视图只是根据用户是否登录返回登录/注销导航菜单:

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("logoff", "account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()
        <ul class="nav navbar-nav navbar-right">
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-at"></i> @User.Identity.GetUserName() <span class="caret"></span></a>
                <ul class="dropdown-menu" role="menu">
                    <li><a href="~/manage" class="dropdown" title="Manage your account"><i class="fa fa-user fa-lg"></i> Account</a></li>
                    <li class="divider"></li>
                    <li><a href="javascript:document.getElementById('logoutForm').submit()" title="Log out"><i class="fa fa-sign-out fa-lg"></i> Log out</a></li>
                </ul>
            </li>
        </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Sign up", "register", "account", routeValues: null, htmlAttributes: new { @class = "btn btn-signup", id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "login", "account", routeValues: new { returnUrl = @Request.Path }, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

我从我的共享_Layout.cshtml文件中调用此内容:

@{ Html.RenderAction("Index", "Menu"); }

我正在努力实现的是,永远不会缓存该特定菜单项,以便不缓存任何用户信息。但是对于发生缓存的页面,例如我的HomeController

public class HomeController : Controller
{
    [OutputCache(CacheProfile = "OneHour", Location=OutputCacheLocation.Server, VaryByParam = "None")]
    public async Task<ActionResult> Index()
    {
        //..some code
        return View(model);
    }

    [ChildActionOnly]
    [OutputCache(Duration = 86400, VaryByParam = "None")]
    public PartialViewResult Other()
    {
        //some code..
        return PartialView(otherModel);
    }
}

...解决方案不起作用:如果我转到未缓存的页面,导航到注销,然后返回/Home/Index菜单仍然显示我已登录。

我在这里缺少什么? MenuController及其视图是否应该位于Shared文件夹中?

1 个答案:

答案 0 :(得分:1)

[ChildActionOnly][OutputCache(/*with anything other than Duration*/)]在框架源的实现方面非常有限,您必须使用: OutputCacheAttribute基类实现自己的缓存属性类,或创建自动签名当用户关闭页面或其他什么时,这就是我现在能想到的。