简体   繁体   English

缓存索引操作方法时,防止在MVC中缓存布局文件

[英]Prevent caching of layout file in MVC when caching Index action method

I have many create Views in my MVC application. 我的MVC应用程序中有很多创建视图。 I have cached the GET Index action method using [OutputCache] annotation, so that the view is stored in the cache. 我使用[OutputCache]注释缓存了GET Index操作方法,以便将视图存储在缓存中。

I store the details about the currently logged in user in the Session , and display the user's first name in the layout after reading it from the Session . 我在Session存储有关当前登录用户的详细信息,并在从Session读取后在布局中显示用户的名字。

The problem is, since I have cached the views, the layout is also cached. 问题是,由于我已缓存视图,因此也会缓存布局。 So even if a different user logs in, the first name of the previous user is visible, because the layout was cached last time. 因此,即使其他用户登录,也可以看到上一个用户的名字,因为上次缓存了布局。

Is there any way to prevent caching of the layout? 有没有办法阻止布局的缓存? Or is there any other way I can stop the first name display from getting cached? 或者有没有其他方法可以阻止第一个名称显示缓存?

I thought about using VaryByCustom , but I am not sure what to do in the GetVaryByCustomString method that I will need to override. 我想过使用VaryByCustom ,但我不确定在GetVaryByCustomString方法中该怎么做才需要覆盖。

What would be the best approach to prevent caching of the layout, or alternately, varying the cache by user? 什么是防止布局缓存的最佳方法,或者用户改变缓存的最佳方法是什么?

EDIT: 编辑:

I must clarify that I am using my own custom user management logic. 我必须澄清我正在使用自己的自定义用户管理逻辑。 I have my own Users table in the database and I retrieve relevant data on login and store it in Session . 我在数据库中有自己的Users表,我在登录时检索相关数据并将其存储在Session

Here's one way you could use the GetVaryByCustom function in Global.asax. 这是在Global.asax中使用GetVaryByCustom函数的一种方法。

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        var varyString = string.Empty;

        if(context.User.Identity.IsAuthenticated)
        {
            varyString += context.User.Identity.Name;
        }

        return varyString;
    }

What you could also do is get the user information with an ajax request and insert it using javascript, that way you don't need to recache the page for each user. 您还可以做的是使用ajax请求获取用户信息并使用javascript插入它,这样您就不需要为每个用户重新缓存页面。 Personally I would go with this approach if the username is the only thing that differs. 我个人会采用这种方法,如果用户名是唯一不同的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM